lua-users home
lua-l archive

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

> 1) I have a C function called Gui_AddScreen and I want it to return a
> pointer to a screen.  I can then use this in other calls in the
> script so I could call Gui_CloseScreen( titleScreen ).  Is this just
> a lightuserdata?  Or would I have to use something else?

That mainly depends on lifetime of the screen object.  If the screen object
is completely managed by the C side, then a lightuserdata is probably
sufficient.  Since a lightuserdata can't have a metatable, it lacks a
garbage collection entry point and also `get' and `set' access support (see
__gc, __index and __newindex metamethods).

What works very well --especially if you want to relate more data to the
screen in your Lua script-- is to wrap your lightuserdata screen in a lua
table, something like this:

-- a screen's metatable
local screen_meta_table = {
    __index = ...,
    __newindex = ...,

-- table to cache screen objects by their c_screen lightuserdata...
local screens = setmetatable({}, {__mode = "v"})

-- wrap a lightuserdata screen
function make_screen(c_screen)
    local s = screens[c_screen]

    if s == nil then
        s = {
            __screen = c_screen,
        setmetatable(s, screen_meta_table)
        screens[c_screen] = s

    return s

You still can't add a __gc method though (it has no effect for Lua tables).
By adding the appropriate entries in the local_screen_meta_table you can do
stuff like:

    screen.width = 100


> 2) I'm writing a shoot em up and want the ai controlled by lua
> scripts.  Is there a recommended way of implementing lots of scripts
> to run at once?  and for this kind of circumstance, I guess it's
> quite a common thing people are doing.  Ideally the scripts would
> also be able to be paused midway.

This depends on your taste.  Personally I prefer a state-based approach in
which events trigger (short) actions, depending on an object's state.  This
state is easily maintained through Lua's excellent support for closures and
upvalues.  You'll probably find many more references on this subject in the
list that propose coroutines for this purpose instead (to halt a script

Also, in my experience it is better to keep a single state (including its
coroutines) single-threaded and use separate (main) states per thread that
marshal data whenever necessary.