lua-users home
lua-l archive

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


> I have not so many knowledge of Lua and Lua/C bindings packages
> like tolua, Luna, LuaWarapper and so on. And the question is: how quick
> and fast do the *direct* binding between Lua data and C structures to access
> this data from C?
>
> For example, I have "smart" Lua-based configuration file, like
>
>  Faults = {
>       [1000] = {title="message1", type=20},
>       [2000] = {title="message2", type=30}
>  }
>
> And I want to access this data directly from my C-code, like
>
>  struct faults {
>    char *title;
>    int type;
>  } *Faults;
>  lua_dofile("faults.lua"); // run config file to init the above Faults
> variable
>  char *str = Faults[1000]->title; // and now get directly the field
>
> I walked through tolua docs (and alternate bindings packages), but they are
> pointed more on access C-data/functions from Lua, and I need vice versa
> functionality.

Hi Ilja,
    A solution would would be to expose a very simple C API to allow you to
set your fault database/array and then do all of your configuration in Lua.

eg. C:
/* C interface ... however you like */
void setFault(int nb, char *title, int type);
void setFaultTitle(int nb, char *title);
void setFaultType(int nb, int type);

toLua.pkg file:
void setFault(int nb, char *title, int type);
void setFaultTitle(int nb, char *title);
void setFaultType(int nb, int type);

Then you parse the faults: ie. lua_dofile("faults.lua") using your format ie.

Faults = {
      [1000] = {title="message1", type=20},
      [2000] = {title="message2", type=30}
}

Then get Lua to set your fault array: eg. lua_dofile("setfault.lua")

-- untested code
for k,v in Faults do
    -- you may want to ensure values exist ie.
    assert( v.title, "No title given for fault: "..k)
    assert( v.type, "No title given for fault: "..k)
    -- or you could ignore asserts and just set defaults for unset values
    local title = v.title or "<No title specified>"
    loca typ = v.type or "<No type specified>"
    setFault(k, title, typ)
end

Faults = nil  -- we dont need that anymore
-- if you close lua state this is somewhat redundant

The above code could be included in you toLua binding using the $[ ... $]
(think thats right) syntax, to save having another file.

The advantage of this approach is your configuration is a lot more flexible.
You could have the faults information in Lua table format or some other
structured format which Lua can easily parse. ie. writing parsers in C is a
pain. The data is all resident in C now so no speed problem. This is what I
would call "pushing" the data into your app to be used, rather than "pulling"
the info from a Lua state at runtime.

Regards,
Nick