-
Notifications
You must be signed in to change notification settings - Fork 142
0.1 Hello Erlang
The Lua interpreter runs entirely inside its own Virtual Machine implemented in Erlang/OTP, however by itself has no access to any Erlang functions or modules.
This means that the only way to extend the reach of a Lua script is by filling the tables in the interpreter state with Lua functions that can reach over that boundary.
On the most basic level the standard libraries (luerl_lib_...
) provide some of those functions. When luerl:init()
is run to create a new Lua state those libraries get loaded and their functions added to the related tables, luerl_lib_io
is loaded to io
and so on.
That is a good start for basic programs but in the case we use luerl
to extend our own program with scripting capabilities we need more. Adding our own functions (that call our Erlang logic) can be done by using luerl:set_table/3
with a function as the second argument.
A few words should be said about how functions are handled in Luerl. Here a Lua function maps to an Erlang function with two arguments:
- the list of arguments passed to the Lua function
- the current state of the Lua interpreter
It then does it's work and return a tuple of two arguments:
- a list of return values
- the new state of the Lua interpreter
So the call:
add(1, 2) # => 3
would look like this for the Erlang code interpreting it:
add([1, 2], St) ->
{[1 + 2], St}
We can return a few value types from a function (as each element of the return list):
- a number, always be treated as a float
- a binary string
- a table, a list of tuples where the first argument is a key and the second is its value.
- a list (which will then be translated into a table with integer indexes)
- a function (of
arity/2
)