HORIZON HASKELLDocslts/ghc-9.10.x248f8f02026-10-05Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · 248f8f0 · 2026-10-05

Modulehslua-2.3.1Haskell2010

HsLua

Functions and utilities enabling the seamless integration of a Lua interpreter into a Haskell project.

This module combines and re-exports the functionality of the HsLua framework. Basic access to the Lua API is provided by Lua.Core from Hackage package lua.

  • 51 types
  • 5 classes
  • 295 values
  • Packagehslua-2.3.1
  • Exports352
  • LanguageHaskell2010
  • LicenceMIT
  • SourceHsLua.hs

Core functionality

169 declarations
typetype Lua a = LuaE Exception a
#

A Lua operation.

This type is suitable for most users. It uses a default exception for error handling. Users who need more control over error handling can use LuaE with a custom error type instead.

newtypenewtype LuaE e a
#

A Lua computation. This is the base type used to run Lua programs of any kind. The Lua state is handled automatically, but can be retrieved via state.

Instances12MonadReader, Exposable, Monad, Functor, MonadFail, Applicative, …

Compares two Lua values. Returns True if the value at index idx1 satisfies op when compared with the value at index idx2, following the semantics of the corresponding Lua operator (that is, it may call metamethods). Otherwise returns False. Also returns False if any of the indices is not valid.

The value of op must be of type RelationalOperator:

EQ: compares for equality (==) LT: compares for less than (<) LE: compares for less or equal (<=)

Wraps hslua_compare. See also lua_compare.

valueconcat :: LuaError e => NumArgs -> LuaE e ()
#

Concatenates the n values at the top of the stack, pops them, and leaves the result at the top. If n is 1, the result is the single value on the stack (that is, the function does nothing); if n is 0, the result is the empty string. Concatenation is performed following the usual semantics of Lua (see §3.4.6 of the Lua manual).

Wraps hslua_concat. See also lua_concat.

classclass Exception e => LuaError e where
#

Any type that you wish to use for error handling in HsLua must be an instance of the LuaError class.

Methods

  • popException :: LuaE e e

    Converts the error at the top of the stack into an exception and pops the error off the stack.

    This function is expected to produce a valid result for any Lua value; neither a Haskell exception nor a Lua error may result when this is called.

  • pushException :: e -> LuaE e ()

    Pushes an exception to the top of the Lua stack. The pushed Lua object is used as an error object, and it is recommended that calling tostring() on the object produces an informative message.

  • luaException :: String -> e

    Creates a new exception with the given message.

Instances1LuaError
newtypenewtype Name
#

Name of a function, table field, or chunk; the name must be valid UTF-8 and may not contain any nul characters.

Implementation note: this is a newtype instead of a simple type Name = ByteString alias so we can define a UTF-8 based IsString instance. Non-ASCII users would have a bad time otherwise.

Constructors

Instances5Eq, Ord, Show, IsString, Semigroup
  • Eq NameDefined in hslua-core-2.3.2 · HsLua.Core.Types
  • Ord NameDefined in hslua-core-2.3.2 · HsLua.Core.Types
  • Show NameDefined in hslua-core-2.3.2 · HsLua.Core.Types
  • IsString NameDefined in hslua-core-2.3.2 · HsLua.Core.Types
  • Semigroup NameDefined in hslua-core-2.3.2 · HsLua.Core.Types
valuegetfield :: LuaError e => StackIndex -> Name -> LuaE e Type
#

Pushes onto the stack the value t[k], where t is the value at the given stack index. As in Lua, this function may trigger a metamethod for the "index" event (see §2.4 of Lua's manual).

Errors on the Lua side are propagated.

See also lua_getfield.

valueremove :: StackIndex -> LuaE e ()
#

Removes the element at the given valid index, shifting down the elements above this index to fill the gap. This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position.

Wraps lua_remove.

valuesetfield :: LuaError e => StackIndex -> Name -> LuaE e ()
#

Does the equivalent to t[k] = v, where t is the value at the given index and v is the value at the top of the stack.

This function pops the value from the stack. As in Lua, this function may trigger a metamethod for the "newindex" event (see §2.4 of the Lua 5.4 Reference Manual).

Errors on the Lua side are caught and rethrown as a Exception.

See also: lua_setfield.

valueerror :: LuaE e NumResults
#

Signals to Lua that an error has occurred and that the error object is at the top of the stack.

datadata RelationalOperator
#

Lua comparison operations.

Constructors

  • EQ

    Correponds to Lua's equality (==) operator.

  • LT

    Correponds to Lua's strictly-lesser-than (<) operator

  • LE

    Correponds to Lua's lesser-or-equal (<=) operator

Instances3Eq, Ord, Show
newtypenewtype Integer
#

The type of integers in Lua.

By default this type is Int64, but that can be changed to different values in Lua. (See LUA_INT_TYPE in luaconf.h.)

See lua_Integer.

Constructors

Instances11Bounded, Enum, Eq, Integral, Num, Ord, …
datadata Type
#

Enumeration used as type tag. See lua_type.

Constructors

Instances6Bounded, Enum, Eq, Ord, Read, Show
  • Bounded TypeDefined in hslua-core-2.3.2 · HsLua.Core.Types
  • Enum TypeDefined in hslua-core-2.3.2 · HsLua.Core.Types
  • Eq TypeDefined in hslua-core-2.3.2 · HsLua.Core.Types
  • Ord TypeDefined in hslua-core-2.3.2 · HsLua.Core.Types
  • Read TypeDefined in hslua-core-2.3.2 · HsLua.Core.Types
  • Show TypeDefined in hslua-core-2.3.2 · HsLua.Core.Types
valueinsert :: StackIndex -> LuaE e ()
#

Moves the top element into the given valid index, shifting up the elements above this index to open space. This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position.

Wraps lua_insert.

valuecheckstack'
  1. :: LuaError e
  2. => Int

    sz (requested additional size)

  3. -> String

    msg

  4. -> LuaE e ()
#

Grows the stack size to top + sz elements, raising an error if the stack cannot grow to that size. msg is an additional text to go into the error message (or the empty string for no additional text).

valuedofile :: Maybe FilePath -> LuaE e Status
#

Loads and runs the given file. Note that the filepath is interpreted by Lua, not Haskell. The resulting chunk is named using the UTF8 encoded filepath.

valuedostring :: ByteString -> LuaE e Status
#

Loads and runs the given string.

Returns OK on success, or an error if either loading of the string or calling of the thunk failed.

valuegetmetafield
  1. :: StackIndex

    obj

  2. -> Name

    e

  3. -> LuaE e Type
#

Pushes onto the stack the field e from the metatable of the object at index obj and returns the type of the pushed value. If the object does not have a metatable, or if the metatable does not have this field, pushes nothing and returns TypeNil.

Wraps luaL_getmetafield.

valuegetsubtable
  1. :: LuaError e
  2. => StackIndex

    idx

  3. -> Name

    fname

  4. -> LuaE e Bool
#

Ensures that the value t[fname], where t is the value at index idx, is a table, and pushes that table onto the stack. Returns True if it finds a previous table there and False if it creates a new table.

valueloadbuffer
  1. :: ByteString

    Program to load

  2. -> Name

    chunk name

  3. -> LuaE e Status
#

Loads a ByteString as a Lua chunk.

This function returns the same results as load. name is the chunk name, used for debug information and error messages. Note that name is used as a C string, so it may not contain null-bytes.

Wraps luaL_loadbuffer.

valueloaded :: Name
#

Key to the registry field that holds the table of loaded modules.

valueloadfile
  1. :: Maybe FilePath

    filename

  2. -> LuaE e Status
#

Loads a file as a Lua chunk. This function uses lua_load (see load) to load the chunk in the file named filename. If filename is Nothing, then it loads from the standard input. The first line in the file is ignored if it starts with a #.

The string mode works as in function load.

This function returns the same results as load, but it has an extra error code ErrFile for file-related errors (e.g., it cannot open or read the file).

As load, this function only loads the chunk; it does not run it.

See luaL_loadfile.

valueloadstring :: ByteString -> LuaE e Status
#

Loads a string as a Lua chunk. This function uses lua_load to load the chunk in the given ByteString. The given string may not contain any NUL characters.

This function returns the same results as lua_load (see load).

Also as load, this function only loads the chunk; it does not run it.

See luaL_loadstring.

valuenewmetatable :: Name -> LuaE e Bool
#

If the registry already has the key tname, returns False. Otherwise, creates a new table to be used as a metatable for userdata, adds to this new table the pair __name = tname, adds to the registry the pair [tname] = new table, and returns True. (The entry __name is used by some error-reporting functions.)

In both cases pushes onto the stack the final value associated with tname in the registry.

The value of tname is used as a C string and hence must not contain null bytes.

Wraps luaL_newmetatable.

valuenewstate :: IO State
#

Creates a new Lua state. It calls lua_newstate with an allocator based on the standard C realloc function and then sets a panic function (see §4.4 of the Lua 5.4 Reference Manual) that prints an error message to the standard error output in case of fatal errors.

Wraps hsluaL_newstate. See also: luaL_newstate.

valuepreload :: Name
#

Key to the registry field that holds the table of loader functions.

valueref :: StackIndex -> LuaE e Reference
#

Creates and returns a reference, in the table at index t, for the object at the top of the stack (and pops the object).

A reference is a unique integer key. As long as you do not manually add integer keys into table t, ref ensures the uniqueness of the key it returns. You can retrieve an object referred by reference r by calling rawgeti t r. Function unref frees a reference and its associated object.

If the object at the top of the stack is nil, ref returns the constant refnil. The constant noref is guaranteed to be different from any reference returned by ref.

Wraps luaL_ref.

valuerequiref
  1. :: LuaError e
  2. => Name

    modname

  3. -> CFunction

    openf

  4. -> Bool

    glb

  5. -> LuaE e ()
#

If modname is not already present in package.loaded. calls function openf with string modname as an argument and sets the call result in package.loaded[modname], as if that function has been called through require.

If glb is true, also stores the module into global modname.

Leaves a copy of the module on the stack.

See requirehs for a version intended to be used with Haskell actions.

Converts any Lua value at the given index to a ByteString in a reasonable format. The resulting string is pushed onto the stack and also returned by the function.

If the value has a metatable with a __tostring field, then tolstring' calls the corresponding metamethod with the value as argument, and uses the result of the call as its result.

Wraps hsluaL_tolstring.

valuetraceback :: State -> Maybe ByteString -> Int -> LuaE e ()
#

Creates and pushes a traceback of the stack L1. If a message is given it is appended at the beginning of the traceback. The level parameter tells at which level to start the traceback.

Wraps luaL_traceback.

valueunref
  1. :: StackIndex

    idx

  2. -> Reference

    ref

  3. -> LuaE e ()
#

Releases reference ref from the table at index idx (see ref). The entry is removed from the table, so that the referred object can be collected. The reference ref is also freed to be used again.

Wraps luaL_unref. See also: luaL_unref.

valuewhere'
  1. :: Int

    lvl

  2. -> LuaE e ()
#

Pushes onto the stack a string identifying the current position of the control at level lvl in the call stack. Typically this string has the following format:

chunkname:currentline:

Level 0 is the running function, level 1 is the function that called the running function, etc.

This function is used to build a prefix for error messages.

Pushes Haskell function as a callable userdata. All values created will be garbage collected. The function should behave similar to a CFunction.

Error conditions should be indicated by raising a catchable exception or by returning the result of Lua.error.

Example:

mod23 :: Lua NumResults
mod23 = do
  mn <- tointeger (nthBottom 1)
  case mn of
    Nothing -> pushstring "expected an integer" *> error
    Just n  -> pushinteger (n `mod` 23)
pushHaskellFunction mod23
setglobal "mod23"
valuepushPreCFunction :: PreCFunction -> LuaE e ()
#

Converts a pre C function to a Lua function and pushes it to the stack.

Pre C functions collect parameters from the stack and return a CInt that represents number of return values left on the stack. See CFunction for more info.

valuegetupvalue
  1. :: StackIndex

    funcindex

  2. -> Int

    n

  3. -> LuaE e (Maybe Name)
#

Gets information about the n-th upvalue of the closure at index funcindex. It pushes the upvalue's value onto the stack and returns its name. Returns Nothing (and pushes nothing) when the index n is greater than the number of upvalues.

See debug.getupvalue for more information about upvalues.

[0, +(0|1), -]

Wraps lua_getupvalue.

valuesetupvalue
  1. :: StackIndex

    funcindex

  2. -> Int

    n

  3. -> LuaE e (Maybe Name)
#

Sets the value of a closure’s upvalue. It assigns the value on the top of the stack to the upvalue and returns its name. It also pops the value from the stack.

Returns Nothing (and pops nothing) when the index n is greater than the number of upvalues.

Parameters funcindex and n are as in the function getupvalue.

[-(0|1), +0, -]

Wraps lua_setupvalue.

Retrieve and pop the top object as an error message. This is very similar to tostring', but ensures that we don't recurse if getting the message failed.

This helpful as a "last resort" method when implementing popException.

Raises an exception that's appropriate when the type of a Lua object at the given index did not match the expected type. The name or description of the expected type is taken as an argument.

valuetry :: Exception e => LuaE e a -> LuaE e (Either e a)
#

Return either the result of a Lua computation or, if an exception was thrown, the error.

valuerequirehs
  1. :: LuaError e
  2. => Name

    modname

  3. -> (Name -> LuaE e ())

    openf

  4. -> LuaE e ()
#

Load a module, defined by a Haskell action, under the given name.

Similar to luaL_requiref: If modname is not already present in package.loaded, calls function openf with string modname as an argument and sets the call result in package.loaded[modname], as if that function has been called through require.

Leaves a copy of the module on the stack.

valuecall :: LuaError e => NumArgs -> NumResults -> LuaE e ()
#

Calls a function.

To call a function you must use the following protocol: first, the function to be called is pushed onto the stack; then, the arguments to the function are pushed in direct order; that is, the first argument is pushed first. Finally you call call; nargs is the number of arguments that you pushed onto the stack. All arguments and the function value are popped from the stack when the function is called. The function results are pushed onto the stack when the function returns. The number of results is adjusted to nresults, unless nresults is multret. In this case, all results from the function are pushed. Lua takes care that the returned values fit into the stack space. The function results are pushed onto the stack in direct order (the first result is pushed first), so that after the call the last result is on the top of the stack.

Any error inside the called function is propagated as exception of type e.

The following example shows how the host program can do the equivalent to this Lua code:

a = f("how", t.x, 14)

Here it is in Haskell (assuming the OverloadedStrings language extension):

getglobal "f"         -- function to be called
pushstring  "how"     -- 1st argument
getglobal "t"         -- table to be indexed
getfield (-1) "x"     -- push result of t.x (2nd arg)
remove (-2)           -- remove 't' from the stack
pushinteger 14        -- 3rd argument
call 3 1              -- call 'f' with 3 arguments and 1 result
setglobal "a"         -- set global 'a'

Note that the code above is "balanced": at its end, the stack is back to its original configuration. This is considered good programming practice.

See lua_call.

valuecheckstack :: Int -> LuaE e Bool
#

Ensures that the stack has space for at least n extra slots (that is, that you can safely push up to n values into it). It returns false if it cannot fulfill the request, either because it would cause the stack to be larger than a fixed maximum size (typically at least several thousand elements) or because it cannot allocate memory for the extra space. This function never shrinks the stack; if the stack already has space for the extra slots, it is left unchanged.

Wraps lua_checkstack.

valueclose :: State -> IO ()
#

Destroys all objects in the given Lua state (calling the corresponding garbage-collection metamethods, if any) and frees all dynamic memory used by this state. On several platforms, you may not need to call this function, because all resources are naturally released when the host program ends. On the other hand, long-running programs that create multiple states, such as daemons or web servers, will probably need to close states as soon as they are not needed.

Same as lua_close.

valuecopy :: StackIndex -> StackIndex -> LuaE e ()
#

Copies the element at index fromidx into the valid index toidx, replacing the value at that position. Values at other positions are not affected.

Wraps lua_copy.

valuecreatetable :: Int -> Int -> LuaE e ()
#

Creates a new empty table and pushes it onto the stack. Parameter narr is a hint for how many elements the table will have as a sequence; parameter nrec is a hint for how many other elements the table will have. Lua may use these hints to preallocate memory for the new table. This preallocation is useful for performance when you know in advance how many elements the table will have. Otherwise you can use the function lua_newtable.

Wraps lua_createtable.

valueequal
  1. :: LuaError e
  2. => StackIndex

    index1

  3. -> StackIndex

    index2

  4. -> LuaE e Bool
#

Returns True if the two values in acceptable indices index1 and index2 are equal, following the semantics of the Lua == operator (that is, may call metamethods). Otherwise returns False. Also returns False if any of the indices is non valid. Uses compare internally.

valuegc :: GCControl -> LuaE e Int
#

Controls the garbage collector.

This function performs several tasks, according to the given control command. See the documentation for GCControl.

Wraps lua_gc.

valuegetmetatable :: StackIndex -> LuaE e Bool
#

If the value at the given index has a metatable, the function pushes that metatable onto the stack and returns True. Otherwise, the function returns False and pushes nothing on the stack.

Wraps lua_getmetatable.

valuegettable :: LuaError e => StackIndex -> LuaE e Type
#

Pushes onto the stack the value t[k], where t is the value at the given index and k is the value at the top of the stack.

This function pops the key from the stack, pushing the resulting value in its place. As in Lua, this function may trigger a metamethod for the "index" event (see §2.4 of Lua's manual).

Errors on the Lua side are caught and rethrown.

Wraps hslua_gettable. See also: lua_gettable.

valuegettop :: LuaE e StackIndex
#

Returns the index of the top element in the stack. Because indices start at 1, this result is equal to the number of elements in the stack (and so 0 means an empty stack).

Wraps lua_gettop.

valueload :: Reader -> Ptr () -> Name -> LuaE e Status
#

Loads a Lua chunk (without running it). If there are no errors, load pushes the compiled chunk as a Lua function on top of the stack. Otherwise, it pushes an error message.

The return values of load are:

  • OK: no errors;

  • ErrSyntax: syntax error during pre-compilation;

  • ErrMem: memory allocation error;

  • ErrGcmm: error while running a __gc metamethod. (This error has no relation with the chunk being loaded. It is generated by the garbage collector.)

This function only loads a chunk; it does not run it.

load automatically detects whether the chunk is text or binary, and loads it accordingly (see program luac).

The load function uses a user-supplied reader function to read the chunk (see Reader). The data argument is an opaque value passed to the reader function.

The chunkname argument gives a name to the chunk, which is used for error messages and in debug information (see §4.7). Note that the chunkname is used as a C string, so it may not contain null-bytes.

This is a wrapper of lua_load.

valuenewtable :: LuaE e ()
#

Creates a new empty table and pushes it onto the stack. It is equivalent to createtable 0 0.

See also: lua_newtable.

valuenewuserdatauv
  1. :: Int

    size

  2. -> Int

    nuvalue

  3. -> LuaE e (Ptr ())
#

This function creates and pushes on the stack a new full userdata, with nuvalue associated Lua values, called user values, plus an associated block of raw memory with size bytes. (The user values can be set and read with the functions lua_setiuservalue and lua_getiuservalue.)

The function returns the address of the block of memory. Lua ensures that this address is valid as long as the corresponding userdata is alive (see §2.5). Moreover, if the userdata is marked for finalization (see §2.5.3), its address is valid at least until the call to its finalizer.

This function wraps lua_newuserdatauv.

valuenext :: LuaError e => StackIndex -> LuaE e Bool
#

Pops a key from the stack, and pushes a key–value pair from the table at the given index (the "next" pair after the given key). If there are no more elements in the table, then next returns False (and pushes nothing).

Errors on the Lua side are caught and rethrown as a Exception.

This function wraps hslua_next. See also: lua_next.

valueopenlibs :: LuaE e ()
#

Opens all standard Lua libraries into the current state and sets each library name as a global value.

This function wraps luaL_openlibs.

Calls a function in protected mode.

Both nargs and nresults have the same meaning as in call. If there are no errors during the call, pcall behaves exactly like call. However, if there is any error, pcall catches it, pushes a single value on the stack (the error message), and returns the error code. Like call, pcall always removes the function and its arguments from the stack.

If msgh is Nothing, then the error object returned on the stack is exactly the original error object. Otherwise, when msgh is Just idx, the stack index idx is the location of a message handler. (This index cannot be a pseudo-index.) In case of runtime errors, this function will be called with the error object and its return value will be the object returned on the stack by pcall.

Typically, the message handler is used to add more debug information to the error object, such as a stack traceback. Such information cannot be gathered after the return of pcall, since by then the stack has unwound.

This function wraps lua_pcall.

valuepushcclosure
  1. :: CFunction
  2. -> NumArgs

    n

  3. -> LuaE e ()
#

Pushes a new C closure onto the stack.

When a C function is created, it is possible to associate some values with it, thus creating a C closure (see §3.4); these values are then accessible to the function whenever it is called. To associate values with a C function, first these values should be pushed onto the stack (when there are multiple values, the first value is pushed first). Then pushcclosure is called to create and push the C function onto the stack, with the argument n telling how many values should be associated with the function. pushcclosure also pops these values from the stack.

The maximum value for n is 255.

Wraps lua_pushcclosure.

valuepushcfunction :: CFunction -> LuaE e ()
#

Pushes a C function onto the stack. This function receives a pointer to a C function and pushes onto the stack a Lua value of type function that, when called, invokes the corresponding C function.

Any function to be callable by Lua must follow the correct protocol to receive its parameters and return its results (see CFunction)

Same as flip pushcclosure 0. lua_pushcfunction.

valuepushlightuserdata :: Ptr a -> LuaE e ()
#

Pushes a light userdata onto the stack.

Userdata represent C values in Lua. A light userdata represents a pointer, a Ptr a (i.e., void* in C). It is a value (like a number): you do not create it, it has no individual metatable, and it is not collected (as it was never created). A light userdata is equal to "any" light userdata with the same C address.

Wraps lua_pushlightuserdata.

valuepushstring :: ByteString -> LuaE e ()
#

Pushes the string pointed to by s onto the stack. Lua makes (or reuses) an internal copy of the given string, so the memory at s can be freed or reused immediately after the function returns.

Wraps lua_pushlstring.

valuepushthread :: LuaE e Bool
#

Pushes the current thread onto the stack. Returns True if this thread is the main thread of its state, False otherwise.

Wraps lua_pushthread.

valuerawequal :: StackIndex -> StackIndex -> LuaE e Bool
#

Returns True if the two values in indices idx1 and idx2 are primitively equal (that is, without calling the __eq metamethod). Otherwise returns False. Also returns False if any of the indices are not valid.

Wraps lua_rawequal.

valuerawlen :: StackIndex -> LuaE e Int
#

Returns the raw "length" of the value at the given index: for strings, this is the string length; for tables, this is the result of the length operator (#) with no metamethods; for userdata, this is the size of the block of memory allocated for the userdata; for other values, it is 0.

Wraps lua_rawlen.

valuerawseti :: LuaError e => StackIndex -> Integer -> LuaE e ()
#

Does the equivalent of t[i] = v, where t is the table at the given index and v is the value at the top of the stack.

This function pops the value from the stack. The assignment is raw, that is, it does not invoke the __newindex metamethod.

Wraps lua_rawseti.

valuereplace :: StackIndex -> LuaE e ()
#

Moves the top element into the given valid index without shifting any element (therefore replacing the value at that given index), and then pops the top element.

Wraps lua_replace.

valuerotate
  1. :: StackIndex
    idx
  2. -> Int
    n
  3. -> LuaE e ()
#

Rotates the stack elements between the valid index idx and the top of the stack. The elements are rotated n positions in the direction of the top, for a positive n, or -n positions in the direction of the bottom, for a negative n. The absolute value of n must not be greater than the size of the slice being rotated. This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position.

https://www.lua.org/manual/5.4/manual.html#lua_rotate

valuesetiuservalue
  1. :: StackIndex

    index

  2. -> Int

    n

  3. -> LuaE e Bool
#

Pops a value from the stack and sets it as the new n-th user value associated to the full userdata at the given index. Returns 0 if the userdata does not have that value.

Wraps lua_setiuservalue.

valuesettable :: LuaError e => StackIndex -> LuaE e ()
#

Does the equivalent to t[k] = v, where t is the value at the given index, v is the value at the top of the stack, and k is the value just below the top.

This function pops both the key and the value from the stack. As in Lua, this function may trigger a metamethod for the "newindex" event (see §2.4 of the Lua 5.4 Reference Manual).

Errors on the Lua side are caught and rethrown.

Wraps hslua_settable.

valuesettop :: StackIndex -> LuaE e ()
#

Accepts any index, or 0, and sets the stack top to this index. If the new top is larger than the old one, then the new elements are filled with nil. If index is 0, then all stack elements are removed.

Wraps lua_settop.

valuesetwarnf
  1. :: WarnFunction

    f

  2. -> Ptr ()

    ud

  3. -> LuaE e ()
#

Sets the warning function to be used by Lua to emit warnings (see WarnFunction). The ud parameter sets the value ud passed to the warning function.

valuestatus :: LuaE e Status
#

Returns the status of this Lua thread.

The status can be OK for a normal thread, an error value if the thread finished the execution of a lua_resume with an error, or Yield if the thread is suspended.

You can only call functions in threads with status OK. You can resume threads with status OK (to start a new coroutine) or Yield (to resume a coroutine).

Wraps lua_status.

valuetoboolean :: StackIndex -> LuaE e Bool
#

Converts the Lua value at the given index to a haskell boolean value. Like all tests in Lua, toboolean returns True for any Lua value different from false and nil; otherwise it returns False. (If you want to accept only actual boolean values, use isboolean to test the value's type.)

Wraps lua_toboolean.

valuetointeger :: StackIndex -> LuaE e (Maybe Integer)
#

Converts the Lua value at the given acceptable index to the signed integral type Integer. The Lua value must be an integer, a number or a string convertible to an integer (see §3.4.3 of the Lua 5.4 Reference Manual); otherwise, tointeger returns Nothing.

If the number is not an integer, it is truncated in some non-specified way.

Wraps lua_tointegerx. See also: lua_tointeger.

valuetopointer :: StackIndex -> LuaE e (Ptr ())
#

Converts the value at the given index to a generic C pointer (void*). The value can be a userdata, a table, a thread, or a function; otherwise, lua_topointer returns nullPtr. Different objects will give different pointers. There is no way to convert the pointer back to its original value.

Typically this function is used only for hashing and debug information.

Wraps lua_topointer.

valuetouserdata :: StackIndex -> LuaE e (Maybe (Ptr a))
#

If the value at the given index is a full userdata, returns its block address. If the value is a light userdata, returns its pointer. Otherwise, returns Nothing..

Wraps lua_touserdata.

newtypenewtype GCManagedState
#

Wrapper of a Lua state whose lifetime is managed by the Haskell garbage collector and has a finalizer attached. This means that the state does not have to be closed explicitly, but will be closed automatically when the value is garbage collected in Haskell.

valuerun :: LuaE e a -> IO a
#

Run Lua computation using the default HsLua state as starting point. Exceptions are masked, thus avoiding some issues when using multiple threads. All exceptions are passed through; error handling is the responsibility of the caller.

valuerunEither :: Exception e => LuaE e a -> IO (Either e a)
#

Run the given Lua computation; exceptions raised in Haskell code are caught, but other exceptions (user exceptions raised in Haskell, unchecked type errors, etc.) are passed through.

datadata Status
#

Lua status values.

Constructors

  • OK

    success

  • Yield

    yielding / suspended coroutine

  • ErrRun

    a runtime rror

  • ErrSyntax

    syntax error during precompilation

  • ErrMem

    memory allocation (out-of-memory) error.

  • ErrErr

    error while running the message handler.

  • ErrFile

    opening or reading a file failed.

Instances2Eq, Show
  • Eq StatusDefined in hslua-core-2.3.2 · HsLua.Core.Types
  • Show StatusDefined in hslua-core-2.3.2 · HsLua.Core.Types
datadata GCControl
#

Commands to control the garbage collector.

Constructors

  • GCStop

    stops the garbage collector.

  • GCRestart

    restarts the garbage collector

  • GCCollect

    performs a full garbage-collection cycle.

  • GCCount

    returns the current amount of memory (in Kbytes) in use by Lua.

  • GCCountb

    returns the remainder of dividing the current amount of bytes of memory in use by Lua by 1024.

  • GCStep CInt

    performs an incremental step of garbage collection, corresponding to the allocation of stepsize Kbytes.

  • GCInc CInt CInt CInt

    Changes the collector to incremental mode with the given parameters (see <https://www.lua.org/manual/5.4/manual.html#2.5.1 §2.5.1>). Returns the previous mode (LUA_GCGEN or LUA_GCINC). Parameters: pause, stepmul, and stepsize.

  • GCGen CInt CInt

    Changes the collector to generational mode with the given parameters (see <https://www.lua.org/manual/5.4/manual.html#2.5.2 §2.5.2>). Returns the previous mode (LUA_GCGEN or LUA_GCINC).

  • GCIsRunning

    returns a boolean that tells whether the collector is running (i.e., not stopped).

Instances3Eq, Ord, Show
  • Eq GCControlDefined in hslua-core-2.3.2 · HsLua.Core.Types
  • Ord GCControlDefined in hslua-core-2.3.2 · HsLua.Core.Types
  • Show GCControlDefined in hslua-core-2.3.2 · HsLua.Core.Types
valuenoref :: Int
#

Value signaling that no reference was found.

valuerefnil :: Int
#

Value signaling that no reference was created.

valuerunWith :: State -> LuaE e a -> IO a
#

Run Lua computation with the given Lua state. Exception handling is left to the caller; resulting exceptions are left unhandled.

valueunsafeRunWith :: State -> LuaE e a -> IO a
#

Run the given operation, but crash if any Haskell exceptions occur.

This function is identical to runWith; it exists for backwards compatibility.

valuefromuserdata
  1. :: StackIndex

    stack index of userdata

  2. -> Name

    expected name of userdata object

  3. -> LuaE e (Maybe a)
#

Retrieves a Haskell object from userdata at the given index. The userdata must have the given name.

valuenewhsuserdatauv
  1. :: a

    Haskell object

  2. -> Int

    number of extra userdata values

  3. -> LuaE e ()
#

Creates a new userdata wrapping the given Haskell object. The userdata is pushed to the top of the stack.

valuenewudmetatable :: Name -> LuaE e Bool
#

Creates and registers a new metatable for a userdata-wrapped Haskell value; checks whether a metatable of that name has been registered yet and uses the registered table if possible.

Returns True if a new metatable was created, and False otherwise.

Using a metatable created by this functions ensures that the pointer to the Haskell value will be freed when the userdata object is garbage collected in Lua.

The name may not contain a nul character.

valueputuserdata
  1. :: StackIndex

    index

  2. -> Name

    name

  3. -> a

    new value

  4. -> LuaE e Bool
#

Replaces the Haskell value contained in the userdata value at index. Checks that the userdata is of type name and returns True on success, or False otherwise.

valuesetwarnf' :: LuaError e => (ByteString -> LuaE e ()) -> LuaE e ()
#

Sets a warning function. This is a simplified version of lua_setwarnf. The given function is called with the concatenated warning components as the single argument.

Control messages are handled internally and are not passed on the warning hook. As with the default warning function, the control messages @on and @off can switch error reporting to stderr on and off. The given Haskell function will be called in either case, even when the error is not written to stderr.

Wraps hsluaL_setwarnf.

methodliftIO :: IO a -> m a
#

Lift a computation from the IO monad. This allows us to run IO computations in any monadic stack, so long as it supports these kinds of operations (i.e. IO is the base monad for the stack).

Example
import Control.Monad.Trans.State -- from the "transformers" library

printState :: Show s => StateT s IO ()
printState = do
  state <- get
  liftIO $ print state

Had we omitted liftIO, we would have ended up with this error:

• Couldn't match type ‘IO’ with ‘StateT s IO’
 Expected type: StateT s IO ()
   Actual type: IO ()

The important part here is the mismatch between StateT s IO () and IO ().

Luckily, we know of a function that takes an IO a and returns an (m a): liftIO, enabling us to run the program and see the expected results:

> evalStateT printState "hello"
"hello"

> evalStateT printState 3
3

Type for C functions.

In order to communicate properly with Lua, a C function must use the following protocol, which defines the way parameters and results are passed: a C function receives its arguments from Lua in its stack in direct order (the first argument is pushed first). So, when the function starts, Lua.Functions.lua_gettop returns the number of arguments received by the function. The first argument (if any) is at index 1 and its last argument is at index Lua.Functions.lua_gettop. To return values to Lua, a C function just pushes them onto the stack, in direct order (the first result is pushed first), and returns the number of results. Any other value in the stack below the results will be properly discarded by Lua. Like a Lua function, a C function called by Lua can also return many results.

See lua_CFunction.

Instances2Peekable, Pushable
newtypenewtype Number
#

The type of floats in Lua.

By default this type is Double, but that can be changed in Lua to a single float or a long double. (See LUA_FLOAT_TYPE in luaconf.h.)

See lua_Number.

Constructors

Instances12Eq, Floating, Fractional, Num, Ord, Read, …
newtypenewtype State
#

An opaque structure that points to a thread and indirectly (through the thread) to the whole state of a Lua interpreter. The Lua library is fully reentrant: it has no global variables. All information about a state is accessible through this structure.

Synonym for lua_State *. See lua_State.

Constructors

Instances4Eq, Generic, Peekable, Rep

Marshalling

58 declarations
valueliftLua :: LuaE e a -> Peek e a
#

Lifts a Lua operation into the Peek monad.

datadata Result a
#

Record to keep track of failure contexts while retrieving objects from the Lua stack.

Constructors

Instances10Monad, Functor, MonadFail, Applicative, Foldable, Traversable, …
  • Monad ResultDefined in hslua-marshalling-2.3.1 · HsLua.Marshalling.Peek
  • Functor ResultDefined in hslua-marshalling-2.3.1 · HsLua.Marshalling.Peek
  • MonadFail ResultDefined in hslua-marshalling-2.3.1 · HsLua.Marshalling.Peek
  • Applicative ResultDefined in hslua-marshalling-2.3.1 · HsLua.Marshalling.Peek
  • Foldable ResultDefined in hslua-marshalling-2.3.1 · HsLua.Marshalling.Peek
  • Traversable ResultDefined in hslua-marshalling-2.3.1 · HsLua.Marshalling.Peek
  • Alternative ResultDefined in hslua-marshalling-2.3.1 · HsLua.Marshalling.Peek
  • MonadPlus ResultDefined in hslua-marshalling-2.3.1 · HsLua.Marshalling.Peek
  • Eq a => Eq (Result a)Defined in hslua-marshalling-2.3.1 · HsLua.Marshalling.Peek
  • Show a => Show (Result a)Defined in hslua-marshalling-2.3.1 · HsLua.Marshalling.Peek
typetype Pusher e a = a -> LuaE e ()
#

Function to push a value to Lua's stack.

newtypenewtype Peek e a
#

Lua operation with an additional failure mode that can stack errors from different contexts; errors are not based on exceptions).

Constructors

Instances7Exposable, Monad, Functor, MonadFail, Applicative, Alternative, …
  • (LuaError e, Pushable a) => Exposable e (Peek e a)Defined in hslua-classes-2.3.1 · HsLua.Class.Exposable
  • Monad (Peek e)Defined in hslua-marshalling-2.3.1 · HsLua.Marshalling.Peek
  • Functor (Peek e)Defined in hslua-marshalling-2.3.1 · HsLua.Marshalling.Peek
  • MonadFail (Peek e)Defined in hslua-marshalling-2.3.1 · HsLua.Marshalling.Peek
  • Applicative (Peek e)Defined in hslua-marshalling-2.3.1 · HsLua.Marshalling.Peek
  • Alternative (Peek e)Defined in hslua-marshalling-2.3.1 · HsLua.Marshalling.Peek
  • MonadPlus (Peek e)Defined in hslua-marshalling-2.3.1 · HsLua.Marshalling.Peek
valuepeekList :: LuaError e => Peeker e a -> Peeker e [a]
#

Reads a numerically indexed table t into a list, where the length of the list is equal to rawlen(t). The operation will fail unless all numerical fields between 1 and rawlen(t) can be retrieved.

valuepushRealFloat :: RealFloat a => a -> LuaE e ()
#

Push a floating point number to the Lua stack. Uses a string representation for all types which do not match the float properties of the Number type.

valuecleanup :: Peek e a -> Peek e a
#

Runs the peek action, resetting the stack top afterwards. This can be used with peek actions that might otherwise leave elements on the stack in case of a failure.

valueforce :: LuaError e => Result a -> LuaE e a
#

Force creation of an unwrapped result, throwing an exception if that's not possible.

valueforcePeek :: LuaError e => Peek e a -> LuaE e a
#

Converts a Peek action into a LuaE action, throwing an exception in case of a peek failure.

valuelastly :: Peek e a -> LuaE e b -> Peek e a
#

Runs the peek action and Lua action in sequence, even if the peek action fails.

valuepeekNil :: Peeker e ()
#

Succeeds if the value at the given index is nil.

valuepeekNoneOrNil :: Peeker e ()
#

Succeeds if the given index is not valid or if the value at this index is nil.

valuepeekPair :: LuaError e => Peeker e a -> Peeker e b -> Peeker e (a, b)
#

Retrieves a value pair from a table. Expects the values to be stored in a numerically indexed table; does not access metamethods.

valuepeekRead :: Read a => Peeker e a
#

Retrieves a value by getting a String from Lua, then using readMaybe to convert the String into a Haskell value.

valuepeekSet :: (LuaError e, Ord a) => Peeker e a -> Peeker e (Set a)
#

Retrieves a Set from an idiomatic Lua representation. A set in Lua is idiomatically represented as a table with the elements as keys. Elements with falsy values are omitted.

valuepeekStringy :: IsString a => Peeker e a
#

Retrieves a String-like value from an UTF-8 encoded Lua string.

This should not be used to peek ByteString values or other values for which construction via fromString can result in loss of information.

valuepeekTriple
  1. :: LuaError e
  2. => Peeker e a
  3. -> Peeker e b
  4. -> Peeker e c
  5. -> Peeker e (a, b, c)
#

Retrieves a value triple from a table. Expects the values to be stored in a numerically indexed table, with no metamethods.

valuetypeChecked
  1. :: Name

    expected type

  2. -> (StackIndex -> LuaE e Bool)

    pre-condition checker

  3. -> Peeker e a
  4. -> Peeker e a
#

Use test to check whether the value at stack index n has the correct type and use peekfn to convert it to a Haskell value if possible. A successfully received value is wrapped using the Right constructor, while a type mismatch results in Left PeekError with the given error message.

valuepushAsTable :: LuaError e => [(Name, a -> LuaE e ())] -> a -> LuaE e ()
#

Pushes an object as a table, defined by a list of field-names/push-function pairs.

valuepushIntegral :: (Integral a, Show a) => a -> LuaE e ()
#

Pushes an Integer to the Lua stack. Values representable as Lua integers are pushed as such; bigger integers are represented using their string representation.

valuepushIterator
  1. :: LuaError e
  2. => (a -> LuaE e NumResults)

    pusher for the values

  3. -> [a]

    list to iterate over lazily

  4. -> LuaE e NumResults
#

Pushes three values to the stack that can be used in a generic for loop to lazily iterate over all values in the list. Keeps the remaining list in a userdata state.

If the values pusher function returns NumResults 0 for a list item, then this item will be skipped and the values for the next item will be pushed.

Module, data, and function packaging

103 declarations
datadata Operation
#

Lua metadata operation types.

Constructors

  • Add

    the addition (+) operation. If any operand for an addition is not a number (nor a string coercible to a number), Lua will try to call a metamethod. First, Lua will check the first operand (even if it is valid). If that operand does not define a metamethod for __add, then Lua will check the second operand. If Lua can find a metamethod, it calls the metamethod with the two operands as arguments, and the result of the call (adjusted to one value) is the result of the operation. Otherwise, it raises an error.

  • Sub

    the subtraction (-) operation. Behavior similar to the addition operation.

  • Mul

    the multiplication (*) operation. Behavior similar to the addition operation.

  • Div

    the division (/) operation. Behavior similar to the addition operation.

  • Mod

    the modulo (%) operation. Behavior similar to the addition operation.

  • Pow

    the exponentiation (^) operation. Behavior similar to the addition operation.

  • Unm

    the negation (unary -) operation. Behavior similar to the addition operation.

  • Idiv

    the floor division (//) operation. Behavior similar to the addition operation.

  • Band

    the bitwise AND (&) operation. Behavior similar to the addition operation, except that Lua will try a metamethod if any operand is neither an integer nor a value coercible to an integer (see §3.4.3).

  • Bor

    the bitwise OR (|) operation. Behavior similar to the bitwise AND operation.

  • Bxor

    the bitwise exclusive OR (binary ~) operation. Behavior similar to the bitwise AND operation.

  • Bnot

    the bitwise NOT (unary ~) operation. Behavior similar to the bitwise AND operation.

  • Shl

    the bitwise left shift (<<) operation. Behavior similar to the bitwise AND operation.

  • Shr

    the bitwise right shift (>>) operation. Behavior similar to the bitwise AND operation.

  • Concat

    the concatenation (..) operation. Behavior similar to the addition operation, except that Lua will try a metamethod if any operand is neither a string nor a number (which is always coercible to a string).

  • Len

    the length (#) operation. If the object is not a string, Lua will try its metamethod. If there is a metamethod, Lua calls it with the object as argument, and the result of the call (always adjusted to one value) is the result of the operation. If there is no metamethod but the object is a table, then Lua uses the table length operation (see §3.4.7). Otherwise, Lua raises an error.

  • Eq

    the equal (==) operation. Behavior similar to the addition operation, except that Lua will try a metamethod only when the values being compared are either both tables or both full userdata and they are not primitively equal. The result of the call is always converted to a boolean.

  • Lt

    the less than (<) operation. Behavior similar to the addition operation, except that Lua will try a metamethod only when the values being compared are neither both numbers nor both strings. The result of the call is always converted to a boolean.

  • Le

    the less equal (<=) operation. Unlike other operations, the less-equal operation can use two different events. First, Lua looks for the __le metamethod in both operands, like in the less than operation. If it cannot find such a metamethod, then it will try the __lt metamethod, assuming that a <= b is equivalent to not (b < a). As with the other comparison operators, the result is always a boolean. (This use of the __lt event can be removed in future versions; it is also slower than a real __le metamethod.)

  • Index

    The indexing access operation table[key]. This event happens when table is not a table or when key is not present in table. The metamethod is looked up in table.

  • Newindex

    The indexing assignment table[key] = value. Like the index event, this event happens when table is not a table or when key is not present in table. The metamethod is looked up in table.

  • Call

    The call operation func(args). This event happens when Lua tries to call a non-function value (that is, func is not a function). The metamethod is looked up in func. If present, the metamethod is called with func as its first argument, followed by the arguments of the original call (args). All results of the call are the result of the operation. (This is the only metamethod that allows multiple results.)

  • Tostring

    The operation used to create a string representation of the object.

  • Pairs

    the operation of iterating over the object's key-value pairs.

  • CustomOperation Name

    a custom operation, with the metamethod name as parameter.

Instances3Eq, Ord, Show
  • Eq OperationDefined in hslua-objectorientation-2.3.1 · HsLua.ObjectOrientation.Operation
  • Ord OperationDefined in hslua-objectorientation-2.3.1 · HsLua.ObjectOrientation.Operation
  • Show OperationDefined in hslua-objectorientation-2.3.1 · HsLua.ObjectOrientation.Operation
valueproperty
  1. :: LuaError e
  2. => Name

    property name

  3. -> Text

    property description

  4. -> (Pusher e b, a -> b)

    how to get the property value

  5. -> (Peeker e b, a -> b -> a)

    how to set a new property value

  6. -> Member e fn a
#

Declares a new read- and writable property.

valueproperty'
  1. :: LuaError e
  2. => Name

    property name

  3. -> TypeSpec

    property type

  4. -> Text

    property description

  5. -> (Pusher e b, a -> b)

    how to get the property value

  6. -> (Peeker e b, a -> b -> a)

    how to set a new property value

  7. -> Member e fn a
#

Declares a new read- and writable typed property.

valuereadonly
  1. :: Name

    property name

  2. -> Text

    property description

  3. -> (Pusher e b, a -> b)

    how to get the property value

  4. -> Member e fn a
#

Creates a read-only object property. Attempts to set the value will cause an error.

valuereadonly'
  1. :: Name

    property name

  2. -> TypeSpec

    property type

  3. -> Text

    property description

  4. -> (Pusher e b, a -> b)

    how to get the property value

  5. -> Member e fn a
#

Creates a read-only object property. Attempts to set the value will cause an error.

datadata Member e fn a
#

A type member, either a method or a variable.

datadata Possible a
#

A property or method which may be available in some instances but not in others.

Constructors

valuedeftypeGeneric
  1. :: Pusher e fn

    function pusher

  2. -> Name

    type name

  3. -> [(Operation, fn)]

    operations

  4. -> [Member e fn a]

    methods

  5. -> UDType e fn a
#

Defines a new type, defining the behavior of objects in Lua. Note that the type name must be unique.

valueinitTypeGeneric
  1. :: LuaError e
  2. => UDTypeWithList e fn a itemtype -> LuaE e ()
  3. -> UDTypeWithList e fn a itemtype
  4. -> LuaE e Name
#

Ensures that the type has been fully initialized, i.e., that all metatables have been created and stored in the registry. Returns the name of the initialized type.

The hook can be used to perform additional setup operations. The function is called as the last step after the type metatable has been initialized: the fully initialized metatable will be at the top of the stack at that point. Note that the hook will not be called if the type's metatable already existed before this function was invoked.

typetype Alias = [AliasIndex]
#

Alias for a different property of this or of a nested object.

typetype ListSpec e a itemtype = ((Pusher e itemtype, a -> [itemtype]), (Peeker e itemtype, a -> [itemtype] -> a))
#

Pair of pairs, describing how a type can be used as a Lua list. The first pair describes how to push the list items, and how the list is extracted from the type; the second pair contains a method to retrieve list items, and defines how the list is used to create an updated value.

typetype UDType e fn a = UDTypeWithList e fn a Void
#

A userdata type, capturing the behavior of Lua objects that wrap Haskell values. The type name must be unique; once the type has been used to push or retrieve a value, the behavior can no longer be modified through this type.

datadata UDTypeWithList e fn a itemtype
#

A userdata type, capturing the behavior of Lua objects that wrap Haskell values. The type name must be unique; once the type has been used to push or retrieve a value, the behavior can no longer be modified through this type.

This type includes methods to define how the object should behave as a read-only list of type itemtype.

datadata Operation
#

Lua metadata operation types.

Constructors

  • Add

    the addition (+) operation. If any operand for an addition is not a number (nor a string coercible to a number), Lua will try to call a metamethod. First, Lua will check the first operand (even if it is valid). If that operand does not define a metamethod for __add, then Lua will check the second operand. If Lua can find a metamethod, it calls the metamethod with the two operands as arguments, and the result of the call (adjusted to one value) is the result of the operation. Otherwise, it raises an error.

  • Sub

    the subtraction (-) operation. Behavior similar to the addition operation.

  • Mul

    the multiplication (*) operation. Behavior similar to the addition operation.

  • Div

    the division (/) operation. Behavior similar to the addition operation.

  • Mod

    the modulo (%) operation. Behavior similar to the addition operation.

  • Pow

    the exponentiation (^) operation. Behavior similar to the addition operation.

  • Unm

    the negation (unary -) operation. Behavior similar to the addition operation.

  • Idiv

    the floor division (//) operation. Behavior similar to the addition operation.

  • Band

    the bitwise AND (&) operation. Behavior similar to the addition operation, except that Lua will try a metamethod if any operand is neither an integer nor a value coercible to an integer (see §3.4.3).

  • Bor

    the bitwise OR (|) operation. Behavior similar to the bitwise AND operation.

  • Bxor

    the bitwise exclusive OR (binary ~) operation. Behavior similar to the bitwise AND operation.

  • Bnot

    the bitwise NOT (unary ~) operation. Behavior similar to the bitwise AND operation.

  • Shl

    the bitwise left shift (<<) operation. Behavior similar to the bitwise AND operation.

  • Shr

    the bitwise right shift (>>) operation. Behavior similar to the bitwise AND operation.

  • Concat

    the concatenation (..) operation. Behavior similar to the addition operation, except that Lua will try a metamethod if any operand is neither a string nor a number (which is always coercible to a string).

  • Len

    the length (#) operation. If the object is not a string, Lua will try its metamethod. If there is a metamethod, Lua calls it with the object as argument, and the result of the call (always adjusted to one value) is the result of the operation. If there is no metamethod but the object is a table, then Lua uses the table length operation (see §3.4.7). Otherwise, Lua raises an error.

  • Eq

    the equal (==) operation. Behavior similar to the addition operation, except that Lua will try a metamethod only when the values being compared are either both tables or both full userdata and they are not primitively equal. The result of the call is always converted to a boolean.

  • Lt

    the less than (<) operation. Behavior similar to the addition operation, except that Lua will try a metamethod only when the values being compared are neither both numbers nor both strings. The result of the call is always converted to a boolean.

  • Le

    the less equal (<=) operation. Unlike other operations, the less-equal operation can use two different events. First, Lua looks for the __le metamethod in both operands, like in the less than operation. If it cannot find such a metamethod, then it will try the __lt metamethod, assuming that a <= b is equivalent to not (b < a). As with the other comparison operators, the result is always a boolean. (This use of the __lt event can be removed in future versions; it is also slower than a real __le metamethod.)

  • Index

    The indexing access operation table[key]. This event happens when table is not a table or when key is not present in table. The metamethod is looked up in table.

  • Newindex

    The indexing assignment table[key] = value. Like the index event, this event happens when table is not a table or when key is not present in table. The metamethod is looked up in table.

  • Call

    The call operation func(args). This event happens when Lua tries to call a non-function value (that is, func is not a function). The metamethod is looked up in func. If present, the metamethod is called with func as its first argument, followed by the arguments of the original call (args). All results of the call are the result of the operation. (This is the only metamethod that allows multiple results.)

  • Tostring

    The operation used to create a string representation of the object.

  • Pairs

    the operation of iterating over the object's key-value pairs.

  • CustomOperation Name

    a custom operation, with the metamethod name as parameter.

Instances3Eq, Ord, Show
  • Eq OperationDefined in hslua-objectorientation-2.3.1 · HsLua.ObjectOrientation.Operation
  • Ord OperationDefined in hslua-objectorientation-2.3.1 · HsLua.ObjectOrientation.Operation
  • Show OperationDefined in hslua-objectorientation-2.3.1 · HsLua.ObjectOrientation.Operation
valuedocsField :: Name
#

Name of the registry field holding the documentation table. The documentation table is indexed by the documented objects, like module tables and functions, and contains documentation strings as values.

The table is an ephemeron table, i.e., an entry gets garbage collected if the key is no longer reachable.

valuedefun :: Name -> a -> HsFnPrecursor e a
#

Begin wrapping a monadic Lua function such that it can be turned into a documented function exposable to Lua.

valuelambda :: a -> HsFnPrecursor e a
#

Just like defun, but uses an empty name for the documented function. Should be used when defining methods or operators.

valueliftPure :: (a -> b) -> a -> LuaE e b
#

Turns a pure function into a monadic Lua function.

The resulting function is strict.

valueliftPure2 :: (a -> b -> c) -> a -> b -> LuaE e c
#

Turns a binary function into a Lua function.

The resulting function is strict in both its arguments.

valueliftPure3 :: (a -> b -> c -> d) -> a -> b -> c -> LuaE e d
#

Turns a ternary function into a Lua function.

The resulting function is strict in all of its arguments.

valueliftPure4 :: (a -> b -> c -> d -> e) -> a -> b -> c -> d -> LuaE err e
#

Turns a quarternary function into a Lua function.

The resulting function is strict in all of its arguments.

valueliftPure5
  1. :: a -> b -> c -> d -> e -> f
  2. -> a
  3. -> b
  4. -> c
  5. -> d
  6. -> e
  7. -> LuaE err f
#

Turns a quinary function into a Lua function.

The resulting function is strict in all of its arguments.

valueoptionalParameter
  1. :: Peeker e a

    method to retrieve the value from Lua

  2. -> TypeSpec

    expected Lua type

  3. -> Text

    parameter name

  4. -> Text

    parameter description

  5. -> Parameter e (Maybe a)
#

Deprecated. Use `opt (parameter ...)` instead.

Creates an optional parameter.

DEPRECATED: Use opt (parameter ...) instead.

valuetoHsFnPrecursor :: StackIndex -> Name -> a -> HsFnPrecursor e a
#

Create a HaskellFunction precursor from a monadic function, selecting the stack index after which the first function parameter will be placed.

typetype DocumentedTypeWithList e a itemtype = UDTypeWithList e (DocumentedFunction e) a itemtype
#

A userdata type, capturing the behavior of Lua objects that wrap Haskell values. The type name must be unique; once the type has been used to push or retrieve a value, the behavior can no longer be modified through this type.

valueinitType :: LuaError e => DocumentedTypeWithList e a itemtype -> LuaE e Name
#

Ensures that the type has been fully initialized, i.e., that all metatables have been created and stored in the registry. Returns the name of the initialized type.

valueproperty
  1. :: LuaError e
  2. => Name

    property name

  3. -> Text

    property description

  4. -> (Pusher e b, a -> b)

    how to get the property value

  5. -> (Peeker e b, a -> b -> a)

    how to set a new property value

  6. -> Member e fn a
#

Declares a new read- and writable property.

valueproperty'
  1. :: LuaError e
  2. => Name

    property name

  3. -> TypeSpec

    property type

  4. -> Text

    property description

  5. -> (Pusher e b, a -> b)

    how to get the property value

  6. -> (Peeker e b, a -> b -> a)

    how to set a new property value

  7. -> Member e fn a
#

Declares a new read- and writable typed property.

valuereadonly
  1. :: Name

    property name

  2. -> Text

    property description

  3. -> (Pusher e b, a -> b)

    how to get the property value

  4. -> Member e fn a
#

Creates a read-only object property. Attempts to set the value will cause an error.

valuereadonly'
  1. :: Name

    property name

  2. -> TypeSpec

    property type

  3. -> Text

    property description

  4. -> (Pusher e b, a -> b)

    how to get the property value

  5. -> Member e fn a
#

Creates a read-only object property. Attempts to set the value will cause an error.

datadata Member e fn a
#

A type member, either a method or a variable.

datadata Possible a
#

A property or method which may be available in some instances but not in others.

Constructors

datadata Property e a
#

A read- and writable property on a UD object.

Type classes

9 declarations
classclass LuaError e => Exposable e a where
#

Operations and functions that can be pushed to the Lua stack. This is a helper function not intended to be used directly. Use the toHaskellFunction wrapper instead.

Methods

  • partialApply :: StackIndex -> a -> Peek e NumResults

    Helper function, called by toHaskellFunction. Should do a partial application of the argument at the given index to the underlying function. Recurses if necessary, causing further partial applications until the operation is a easily exposable to Lua.

Instances4Exposable
valuetoHaskellFunction :: Exposable e a => a -> HaskellFunction e
#

Convert a Haskell function to a function type directly exposable to Lua. Any Haskell function can be converted provided that:

  • all arguments are instances of Peekable

  • return type is LuaE e a, where a is an instance of Pushable

Any exception of type e will be caught.

Important: this does not catch exceptions other than e; exception handling must be done by the Haskell function. Failure to do so will cause the program to crash.

E.g., the following code could be used to handle an Exception of type FooException, if that type is an instance of MonadCatch and Pushable:

toHaskellFunction (myFun `catchM` (\e -> raiseError (e :: FooException)))
valueinvoke :: Invokable a => Name -> a
#

Invoke a Lua function. Use as:

v <- invoke "proc" "abc" (1::Int) (5.0::Double)
classclass Peekable a where
#

A value that can be read from the Lua stack.

Methods

Instances26Peekable, …
classclass Pushable a where
#

A value that can be pushed to the Lua stack.

Methods

  • push :: LuaError e => a -> LuaE e ()

    Pushes a value onto Lua stack, casting it into meaningfully nearest Lua type.

Instances25Pushable, …

Marshal to and from JSON-like structures

7 declarations
valuejsonarray :: Name
#

Name of the registry slot holding the metatable given to array tables. The registry entry can be replaced with a different table if needed.

valuepeekToAeson :: Peeker e (ToAeson e)
#

Gets the ToAeson function from a Lua userdata object.

valuepushToAeson :: Pusher e (ToAeson e)
#

Pushes a function that converts the object at a given index into a Value.

Utility functions

6 declarations
valuegetglobal' :: LuaError e => Name -> LuaE e ()
#

Like getglobal, but knows about packages and nested tables. E.g.

getglobal' "math.sin"

will return the function sin in package math.

valuesetglobal' :: LuaError e => Name -> LuaE e ()
#

Like setglobal, but knows about packages and nested tables. E.g.

pushstring "0.9.4"
setglobal' "mypackage.version"

All tables and fields, except for the last field, must exist.

valuepopValue :: (LuaError e, Peekable a) => LuaE e a
#

Get, then pop the value at the top of the stack. The pop operation is executed even if the retrieval operation failed.

newtypenewtype Optional a
#

Newtype wrapper intended to be used for optional Lua values. Nesting this type is strongly discouraged as missing values on inner levels are indistinguishable from missing values on an outer level; wrong values would be the likely result.

Constructors

Instances2Peekable, Pushable