lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 29/11/12 23:20, Philipp Kraus wrote:
[...]
> I would like to create for each of my individuals an own script, so I need for each script
> one Lua state, do I? I would like to use one Lua state on one thread, so I would like
> to use the Lua state with different Lua scripts. Can I do this?

Ah! Yes.

A Lua state represents a Lua virtual machine. (I'll call it a VM instead
of a Lua state for clarity.) Once created, you can manipulate the VM
from C, doing things like loading scripts into it, calling them, setting
global variables, reading variables, etc.

For example, games frequently use Lua for their game scripting. They
will typically use something like (in pseudocode):

  create VM
  VM.load("gamescript.lua")
  VM.call("init")

  VM.set("running", true)
  while (VM.get("running")
  {
    VM.call("process_frame")
  }
  destroy VM

I would expect one of your threads to do something like this:

  create VM
  script = fetch_script_from_database()
  VM.execute(script)

  for (;;)
  {
    message = wait_for_message()
    VM.set("simulationstate", message.simulationstate)
    VM.call(message.workunit)
    message.simulationstate = VM.get("simulationstate")
    message.reply()
  }

This can all be done from C or C++. Loading a script into the VM is done
with lua_dofile() or lua_dostring(), calling a function that has been
defined in the script is done with lua_call() or lua_pcall(), and
getting and setting a global variable with lua_getglobal() and
lua_setglobal(). See:

http://www.lua.org/manual/5.2/manual.html#4.8

The API is simple but there are gotchas --- the big one is that Lua
distinguishes between *loading* a script and *running* it, and a common
error is to load the script without running it and then discovering that
none of the functions defined in the script are available. There's also
endless tweaks you can do to improve performance; global variables are
simple but not fast.

But everything is there in the documentation, which is dense but excellent.

-- 
┌─── dg@cowlark.com ───── http://www.cowlark.com ─────
│ "Of course, on a sufficiently small planet, 40 km/hr is, in fact,
│ sufficient to punt the elastic spherical cow into low orbit." ---
│ Brooks Moses on r.a.sf.c

Attachment: signature.asc
Description: OpenPGP digital signature