luna

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 29, 2020 License: MIT Imports: 15 Imported by: 0

README

Luna - Wrapping the Moon

Special Thanks

Luna is built on top of the very excellent gopher-lua to provide a Lua state for executing source code inside of your Go library. If you're looking for something more lightweight than Luna then you should look no further than here.

Luna is also powered by a lightweight wrapper for gopher-lua, gopher-luar which uses reflection to enable more flexibility in passing data to and from a Lua state.

Documentation

Index

Constants

View Source
const EnginePoolKey = "engine pool"

EnginePoolKey is the key used in the engine Meta field to store which Pool this engine came from (used to put the engine back in the pool when not in use.

View Source
const EnginePoolMetaKey = "engine pool"

EnginePoolMetaKey is a string value for associating the pool with an engine

Variables

This section is empty.

Functions

This section is empty.

Types

type Engine

type Engine struct {
	Meta    map[string]interface{}
	Options EngineOptions
	// contains filtered or unexported fields
}

Engine is the core interface for interacting with a glua.LState, it provides most methods the base LState provides in a more conveinient way as well as adding new ways to interact with the LState.

func NewEngine

func NewEngine() *Engine

NewEngine creates a new luna engine with the default option values.

func NewEngineWithOptions

func NewEngineWithOptions(options EngineOptions) *Engine

NewEngineWithOptions creates a new engine using the specified options.

func (*Engine) ArgumentError

func (e *Engine) ArgumentError(n int, msg string)

ArgumentError raises an error associated with an invalid argument.

func (*Engine) Call

func (e *Engine) Call(name string, retCount int, params ...interface{}) ([]*Value, error)

Call allows for calling a method by name. The second parameter is the number of return values the function being called should return. These values will be returned in a slice of Value pointers.

func (*Engine) Close

func (e *Engine) Close()

Close will perform a close on the Lua state.

func (*Engine) DoFile

func (e *Engine) DoFile(fn string) error

DoFile runs the file through the Lua interpreter.

func (*Engine) DoString

func (e *Engine) DoString(src string) error

DoString runs the given string through the Lua interpreter.

func (*Engine) False

func (e *Engine) False() *Value

False returns a value for the constant 'false' in Lua.

func (*Engine) Get

func (e *Engine) Get(n int) *Value

Get returns the value at the specified location on the Lua stack.

func (*Engine) GetEnviron

func (e *Engine) GetEnviron() *Value

GetEnviron returns the Environment core table from Lua.

func (*Engine) GetGlobal

func (e *Engine) GetGlobal(name string) *Value

GetGlobal returns the value associated with the given name, or LuaNil

func (*Engine) GetGlobals

func (e *Engine) GetGlobals() *Value

GetGlobals returns the global core table from Lua.

func (*Engine) GetRegistry

func (e *Engine) GetRegistry() *Value

GetRegistry retursn the Registry core table from Lua.

func (*Engine) LoadFile

func (e *Engine) LoadFile(fpath string) (*Value, error)

LoadFile attempts to read the file from the file system and then load it into the engine, returning a function that executes the contents of the file.

func (*Engine) LoadString

func (e *Engine) LoadString(src string) (*Value, error)

LoadString runs the given string through the Lua interpreter, wrapping it in a function that is then returned and it can be executed by calling the returned function.

func (*Engine) MetatableFor

func (e *Engine) MetatableFor(goVal interface{}) *Value

MetatableFor returns the Lua metatable for a given type, allowing it to be modified.

func (*Engine) NewTable

func (e *Engine) NewTable() *Value

NewTable create and returns a new NewTable.

func (*Engine) NewUserData

func (e *Engine) NewUserData(val interface{}, mt interface{}) *Value

NewUserData creates a Lua User Data object from teh given value and metatable value.

func (*Engine) Nil

func (e *Engine) Nil() *Value

Nil returns a value for the constant 'nil' in Lua.

func (*Engine) OpenBase

func (e *Engine) OpenBase()

OpenBase allows the Lua engine to open the base library up for use in scripts.

func (*Engine) OpenChannel

func (e *Engine) OpenChannel()

OpenChannel allows the Lua module for Go channel support to be accessible to scripts.

func (*Engine) OpenCoroutine

func (e *Engine) OpenCoroutine()

OpenCoroutine allows the Lua module for goroutine suppor tto be accessible to scripts.

func (*Engine) OpenDebug

func (e *Engine) OpenDebug()

OpenDebug allows the Lua module support debug features to be accissible in scripts.

func (*Engine) OpenIO

func (e *Engine) OpenIO()

OpenIO allows the input/output Lua module to be accessbile in scripts.

func (*Engine) OpenLibs

func (e *Engine) OpenLibs()

OpenLibs seeds the engine with some basic library access. This should only be used if security isn't necessarily a major concern.

func (*Engine) OpenMath

func (e *Engine) OpenMath()

OpenMath allows the Lua math moduled to be accessible in scripts.

func (*Engine) OpenOS

func (e *Engine) OpenOS()

OpenOS allows the OS Lua module to be accessible in scripts.

func (*Engine) OpenPackage

func (e *Engine) OpenPackage()

OpenPackage allows the Lua module for packages to be used in scripts. TODO: Find out what this does/means.

func (*Engine) OpenString

func (e *Engine) OpenString()

OpenString allows the Lua module for string operations to be used in scripts.

func (*Engine) OpenTable

func (e *Engine) OpenTable()

OpenTable allows the Lua module for table operations to be used in scripts.

func (*Engine) PopBool

func (e *Engine) PopBool() bool

PopBool returns the top of the stack as an actual Go bool.

func (*Engine) PopFloat

func (e *Engine) PopFloat() float64

PopFloat returns the top of the stack as an actual Go float.

func (*Engine) PopFunction

func (e *Engine) PopFunction() *Value

PopFunction is an alias for PopArg, provided for readability when specifying the desired value from the top of the stack.

func (*Engine) PopInt

func (e *Engine) PopInt() int

PopInt returns the top of the stack as an actual Go int.

func (*Engine) PopInt64

func (e *Engine) PopInt64() int64

PopInt64 returns the top of the stack as an actual Go int64.

func (*Engine) PopInterface

func (e *Engine) PopInterface() interface{}

PopInterface returns the top of the stack as an actual Go interface.

func (*Engine) PopNumber

func (e *Engine) PopNumber() *Value

PopNumber is an alias for PopArg, provided for readability when specifying the desired value from the top of the stack.

func (*Engine) PopString

func (e *Engine) PopString() string

PopString returns the top of the stack as an actual Go string value.

func (*Engine) PopTable

func (e *Engine) PopTable() *Value

PopTable is an alias for PopArg, provided for readability when specifying the desired value from the top of the stack.

func (*Engine) PopValue

func (e *Engine) PopValue() *Value

PopValue returns the top value on the Lua stack. This method is used to get arguments given to a Go function from a Lua script. This method will return a Value pointer that can then be converted into an appropriate type.

func (*Engine) PushValue

func (e *Engine) PushValue(val interface{})

PushValue pushes the given Value onto the Lua stack. Use this method when 'returning' values from a Go function called from a Lua script.

func (*Engine) RaiseError

func (e *Engine) RaiseError(err string, args ...interface{})

RaiseError will throw an error in the Lua engine.

func (*Engine) RegisterClass

func (e *Engine) RegisterClass(name string, val interface{})

RegisterClass assigns a new type, but instead of creating it via "TypeName()" it provides a more OO way of creating the object "TypeName.new()" otherwise it's functionally equivalent to RegisterType.

func (*Engine) RegisterClassWithCtor

func (e *Engine) RegisterClassWithCtor(name string, typ interface{}, cons interface{})

RegisterClassWithCtor does the same thing as RegisterClass excep the new function is mapped to the constructor passed in.

func (*Engine) RegisterFunc

func (e *Engine) RegisterFunc(name string, fn interface{})

RegisterFunc registers a Go function with the script. Using this method makes Go functions accessible through Lua scripts.

func (*Engine) RegisterModule

func (e *Engine) RegisterModule(name string, fields map[string]interface{}) *Value

RegisterModule takes the values given, maps them to a LuaTable and then preloads the module with the given name to be consumed in Lua code.

func (*Engine) RegisterType

func (e *Engine) RegisterType(name string, val interface{})

RegisterType creates a construtor with the given name that will generate the given type.

func (*Engine) SecureRequire

func (e *Engine) SecureRequire(validPaths []string)

SecureRequire will set a require function that limits the files that can be loaded into the engine.

func (*Engine) SetField

func (e *Engine) SetField(tbl *Value, key string, val interface{})

SetField applies the value to the given table associated with the given key.

func (*Engine) SetGlobal

func (e *Engine) SetGlobal(name string, val interface{})

SetGlobal allows for setting global variables in the loaded code.

func (*Engine) StackSize

func (e *Engine) StackSize() int

StackSize returns the maximum value currently remaining on the stack.

func (*Engine) TableFromMap

func (e *Engine) TableFromMap(i interface{}) *Value

TableFromMap takes a map of go values and generates a Lua table representing the value.

func (*Engine) TableFromSlice

func (e *Engine) TableFromSlice(i interface{}) *Value

TableFromSlice converts the given slice into a table ready for use in Lua.

func (*Engine) True

func (e *Engine) True() *Value

True returns a value for the constant 'true' in Lua.

func (*Engine) ValueFor

func (e *Engine) ValueFor(val interface{}) *Value

ValueFor takes a Go type and creates a lua equivalent Value for it.

type EngineMutator

type EngineMutator func(*Engine)

EngineMutator will modify an Engine before it goes into the pool. This can run any number of scripts as necessary such as registring libraries, executing code, etc...

type EngineOptions

type EngineOptions struct {
	// OpenLibs determines if the engine should enable the core Lua libraries
	// when creating a new State, if you're looking for security you should not
	// enable this.
	OpenLibs bool

	// FieldCasing defines how the name of a Go struct field should be converted
	// when being passed to Lua.
	FieldCasing NamingConvention

	// MethodCasing defines how the name of a Go struct/interface method should
	// be converted when being passed to Lua.
	MethodCasing NamingConvention
}

EngineOptions allows for customization of a lua.Engine such as altering the names of fields and methods as well as whether or not to open all libraries.

type EnginePool

type EnginePool struct {
	MaxPoolSize int
	Mutator     EngineMutator
	// contains filtered or unexported fields
}

EnginePool represents a grouping of predefined/preloaded engines that can be grabbed for use when Lua scripts need to run.

func NewEnginePool

func NewEnginePool(poolSize int, mutator EngineMutator) *EnginePool

NewEnginePool constructs a new pool with the specific maximum size and the engine mutator. It will seed the pool with one engine.

func (*EnginePool) EachEngine

func (ep *EnginePool) EachEngine(fn func(*Engine))

EachEngine will call the provided handler with each engine. IN NO WAY SHOULD THIS BE USED TO UNDERMINE GET, THIS IS FOR MAINTENANCE.

func (*EnginePool) Get

func (ep *EnginePool) Get() *PooledEngine

Get will fetch the next available engine from the EnginePool. If no engines are available and the maximum number of active engines in the pool have been created yet then the spawner will be invoked to spawn a new engine and return that.

func (*EnginePool) Len

func (ep *EnginePool) Len() int

Len will return the number of engines that have been spawned during the execution fo the pool.

func (*EnginePool) Shutdown

func (ep *EnginePool) Shutdown()

Shutdown will empty the channel, close all generated engines and mark the pool closed.

type Inspecter

type Inspecter interface {
	Inspect(string) string
}

Inspecter defines an type that can respond to the Inspect function. This is similar to fmt.Stringer in that it's a method that returns a string, but the goal with Inspecter over fmt.Stringer is to provide debug information in the string output rather than (potentially) user facing output.

type NamingConvention

type NamingConvention int8

NamingConvention defines how Go names should be converted into Lua names when passing values into the Engine.

const (
	// SnakeCaseAndPascalCase converts all Go names to both their snake_case
	// and Pascal case (ex for 'HelloWorld' you get 'hello_world' and
	// 'HelloWorld')
	SnakeCaseAndPascalCase NamingConvention = iota

	// SnakeCase converts Go names into snake_case only (Default)
	SnakeCase

	// PascalCase converts Go names into Go-exported type case normally
	// (essentially meaning the exported name is unchanged when transitioning
	// to Lua) only.
	PascalCase

	// CamelCase converts Go names into camelCased only.
	CamelCase
)

type PooledEngine

type PooledEngine struct {
	*Engine
	// contains filtered or unexported fields
}

PooledEngine wraps a Lua engine. It's purpose is provide a means with which to return the engine to the EnginePool when it's not longer being used.

func (*PooledEngine) Release

func (pe *PooledEngine) Release()

Release will push the engine back into the queue for available engines for the current PooledEngine as well as nil out the reference to the engine to prevent continued usage of the engine.

type REPL

type REPL struct {
	// contains filtered or unexported fields
}

REPL represent a Read-Eval-Print-Loop

func NewREPL

func NewREPL(eng *Engine, name string) *REPL

NewREPL creates a REPL struct and seeds it with the necessary values to prepare it for use. Uses the default .repl-history file.

func NewREPLWithConfig

func NewREPLWithConfig(config REPLConfig) *REPL

NewREPLWithConfig creates a REPL from the provided configuration.

func (*REPL) Execute

func (r *REPL) Execute(src string)

Execute will take a source string and attempt to execute it in the given engine context.

func (*REPL) NumberPrompt

func (r *REPL) NumberPrompt() string

NumberPrompt returns a formatted prompt to use as the Readline prompt.

func (*REPL) Run

func (r *REPL) Run() error

Run begins the execution fo the read-eval-print-loop. Executing the REPL only ends when an input line matches `.exit` or if an error is encountered.

func (*REPL) StarPrompt

func (r *REPL) StarPrompt() string

StarPrompt generates a similar prompt to the font with the line number in it, but instead of the line number it uses a * character.

type REPLConfig

type REPLConfig struct {
	Engine          *Engine
	HistoryFilePath string
	Name            string
	Prompt          string
}

REPLConfig provides a mean for configuring a lua.REPL value. -- HistoryFilePath is the path to the history file for storing the written

history of the REPL session (optional)

-- Prompt is a fmt string to print as the prompt for each REPL input line.

There is a special format value {n} here where you want the line number
to go, or {name} as a place to inject the name provided (if any).

-- Name is a name given, really only useful when no prompt is given as this

value is injected into the prompt.

type ScriptFunction

type ScriptFunction func(*Engine) int

ScriptFunction is a Go function intended to be called from within Lua code. It receives the Engine that it was called from within as its argument which can be used to extract arguments from the Lua stack. It is expected to push all return values back onto the Lua stack and the function returns the number of return values it pushed.

type ScriptableObject

type ScriptableObject interface {
	ScriptObject() interface{}
}

ScriptableObject defines an interface that returns an object to represent it in a script. For example, in game scripts should not have access to a full Player reference, but instead will receive a "scriptable player" reference that controls what can be done to a player. Most objects returned would be small wrapper objects.

type TableMap

type TableMap map[string]interface{}

TableMap is simple type definition around map[string]interface{} which is a more clear and friendly Go type to use when defining a Table meant to be sent into Lua.

type Value

type Value struct {
	// contains filtered or unexported fields
}

Value is a utility wrapper for lua.LValue that provies conveinient methods for casting.

func (*Value) Append

func (v *Value) Append(value interface{})

Append maps to lua.LTable.Append

func (*Value) AsBool

func (v *Value) AsBool() bool

AsBool returns the Lua boolean representation for an object (this works for non bool Values)

func (*Value) AsFloat

func (v *Value) AsFloat() float64

AsFloat returns the LValue as a Go float64. This method will try to convert the Lua value to a number if possible, if not then LuaNumber(0) is returned.

func (*Value) AsMapStringInterface

func (v *Value) AsMapStringInterface() map[string]interface{}

AsMapStringInterface will work on a Lua Table to convert it into a go map[string]interface. This method is not safe for cyclic objects! You have been warned.

func (*Value) AsNumber

func (v *Value) AsNumber() float64

AsNumber is an alias for AsFloat (Lua calls them "numbers")

func (*Value) AsRaw

func (v *Value) AsRaw() interface{}

AsRaw returns the best associated Go type, ingoring functions and any other odd types. Only concerns itself with string, bool, nil, number and user data types. Tables are again, ignored.

func (*Value) AsSliceInterface

func (v *Value) AsSliceInterface() []interface{}

AsSliceInterface will convert the Lua table value to a []interface{}, extracting Go values were possible and preserving references to tables.

func (*Value) AsString

func (v *Value) AsString() string

AsString returns the LValue as a Go string

func (*Value) Call

func (v *Value) Call(retCount int, argList ...interface{}) ([]*Value, error)

Call invokes the LuaValue as a function (if it is one) with similar behavior to engine.Call. If you're looking to invoke a function on table, then see Value.Invoke

func (*Value) Equals

func (v *Value) Equals(o interface{}) bool

Equals will determine if the *Value is equal to the other value. This also verifies they are from the same *lua.Engine as well.

func (*Value) ForEach

func (v *Value) ForEach(cb func(*Value, *Value))

ForEach maps to lua.LTable.ForEach

func (*Value) FuncLocalName

func (v *Value) FuncLocalName(regno, pc int) (string, bool)

FuncLocalName is a function that returns the local name of a LFunction type if this Value objects holds an LFunction.

func (*Value) Get

func (v *Value) Get(key interface{}) *Value

Get returns the value associated with the key given if the LuaValue wraps a table.

func (*Value) Insert

func (v *Value) Insert(i int, value interface{})

Insert maps to lua.LTable.Insert

func (*Value) Inspect

func (v *Value) Inspect(indent string) string

Inspect is similar to AsString except that it's designed to display values for debug purposes.

func (*Value) Interface

func (v *Value) Interface() interface{}

Interface returns the value of the LUserData

func (*Value) Invoke

func (v *Value) Invoke(key interface{}, retCount int, argList ...interface{}) ([]*Value, error)

Invoke will fetch a funtion value on the table (if we're working with a table, and then attempt to invoke it if it's a function.

func (*Value) IsBool

func (v *Value) IsBool() bool

IsBool returns true if the stored value is a boolean value.

func (*Value) IsFalse

func (v *Value) IsFalse() bool

IsFalse is similar to AsBool except it returns if the Lua value would be considered false in Lua.

func (*Value) IsFunction

func (v *Value) IsFunction() bool

IsFunction returns true if the stored value is a function.

func (*Value) IsMaybeList

func (v *Value) IsMaybeList() bool

IsMaybeList will try and determine if the table _might_ be used as a list. This basically checks the first index (looking for something at 1) so it's not 100% accurate, hence 'Maybe.' Also a list that starts with 'nil' will report as not a list.

func (*Value) IsNil

func (v *Value) IsNil() bool

IsNil will only return true if the Value wraps LNil.

func (*Value) IsNumber

func (v *Value) IsNumber() bool

IsNumber returns true if the stored value is a numeric value.

func (*Value) IsString

func (v *Value) IsString() bool

IsString returns true if the stored value is a string.

func (*Value) IsTable

func (v *Value) IsTable() bool

IsTable returns true if the stored value is a table.

func (*Value) IsTrue

func (v *Value) IsTrue() bool

IsTrue returns whether or not this is a truthy value or not.

func (*Value) IsUserData

func (v *Value) IsUserData() bool

IsUserData returns a bool if the Value is an LUserData

func (*Value) Len

func (v *Value) Len() int

Len maps to lua.LTable.Len

func (*Value) MaxN

func (v *Value) MaxN() int

MaxN maps to lua.LTable.MaxN

func (*Value) Next

func (v *Value) Next(key interface{}) (*Value, *Value)

Next maps to lua.LTable.Next

func (*Value) RawGet

func (v *Value) RawGet(goKey interface{}) *Value

RawGet fetches data from a table, bypassing __index metamethod.

func (*Value) RawSet

func (v *Value) RawSet(goKey interface{}, val interface{})

RawSet bypasses any checks for key existence and sets the value onto the table with the given key.

func (*Value) RawSetInt

func (v *Value) RawSetInt(i int, val interface{})

RawSetInt sets some value at the given integer index value.

func (*Value) Remove

func (v *Value) Remove(pos int) *Value

Remove maps to lua.LTable.Remove

func (*Value) Set

func (v *Value) Set(goKey interface{}, val interface{})

Set will assign the field on the object to the given value.

func (*Value) String

func (v *Value) String() string

String makes Value conform to Stringer

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL