Skip to content
JakobOvrum edited this page Feb 16, 2013 · 5 revisions

LuaD Tutorial - the Lua State

return to the tutorial index

From the Lua manual:

Opaque structure that keeps the whole state of a Lua interpreter. The Lua library is fully reentrant: it has no global variables. All information about a state is kept in this structure.

In LuaD, a Lua state is provided by the LuaState class. Using Lua in a program always begins by creating a Lua state:

auto lua = new LuaState;

LuaState is the entry point to all LuaD functionality. It exposes the two basic windows into Lua: the global table and the registry table. It also exposes the ability to run Lua code or Lua scripts in the current instance. To use the LuaD API, import luad.all. Although not very interesting, a complete program could look like this:

import luad.all;

void main()
{
    auto lua = new LuaState;
}

The global table is used for looking up all non-local variables in Lua code. We can fill the global table with the functionality of the Lua standard library by calling the openLibs method. The print function, which writes to the standard output pipe, is one of the introduced globals. Let's expand the above example:

lua.openLibs();
lua.doString(`print("hello, world!")`);

As seen above, doString lets us run Lua code in our instance. Any errors which may have occurred during execution which weren't handled by Lua are thrown as D exceptions.

Introducing new entries in a table is done by using the index assign operator, reminiscent of doing the same operation in Lua. The global table is available as the globals property of the LuaState:

lua.globals["message"] = "hello, world!";
lua.doString(`print(message)`);

The globals and registry members of LuaState are of type LuaTable. Through the globals table, we can read and write global variables and perform various other table-specific operations. The get, set, opIndex and opIndexAssign methods of LuaState are forwarded to globals for convenience; the next example is equivalent of the previous one:

lua["message"] = "hello, world!";
lua.doString(`print(message)`);

Next chapter - Type Conversions (chapter index)

Clone this wiki locally