lua-users home
lua-l archive

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


It was thus said that the Great Leinen, Rick once stated:
> 
> I have written "C" functions to manage a Lua table that is to be used by a
> Lua script to pass parameters to a "C" function where the parameters are
> sent out a proprietary CAN stack.  The Lua table is created from a "C"
> function before the first lua_pcall is called.  Initially the table is as
> follows:
> 
> messagePayload =
> {
>   isRelativeLevel = 0,
>   isFadeRate = 1,
>   isWaitForGo = 0,
>   isHighestTakePrecedence = 0,
>   priority = 8,
>   fade = 10,
>   channelListCount = 0,
>   Dimmers =
>   {
>     [0] = nil,
>   }
> }

  While Lua can deal with arrays starting with 0, it is traditional to start
with 1.  Also, you don't need to initialize the first element in the array;
just doing a lua_createtable(L,0,0) is enough for that.

> One of the functions that can be called from "C" adds dimmer/level pairs
> to the Dimmers table.  For example, if the LuaScript called the "C"
> function with a dimmer number of 1 and a level of 128, the table would be
> modified as follows:
> 
> messagePayload =
> {
>   isRelativeLevel = 0,
>   isFadeRate = 1,
>   isWaitForGo = 0,
>   isHighestTakePrecedence = 0,
>   priority = 8,
>   fade = 10,
>   channelListCount = 0,
>   Dimmers =
>   {
>     [0] = {dim = 1, lev = 128}
>   }
> }

  Is there some reason why this can't be done in Lua?  Is there some
background processing that happens you set the Dimmers array?  Because that
seems like a bunch of extra work dealing with that in C.  

> Additional dimmer/level pairs can be added.
> 
> My question is this; I would like to be able to modify the values of
> members of the table from Lua, but I do not want Lua to be able to change
> the members or structure of the table, only the "C" functions are allowed
> to do this.  Is this possible?

  For the most part, yes.  Just associate a metatable with a function
__newindex() that either does nothing, or raises an error (depending on
taste).  This will prevent new fields from being added to the table. 
Existing members can be removed, however, by being set to 'nil'.  If you
don't want to deal with that, then you either need to create a proxy table
with a metatable with both __index() and __newindex() methods to manage the
fields.

  But a question: why?  Adding members should not affect your code, and it
would allow the programmer to associate additional information.

  Without knowing more about the problem, it seems like constructing the
table in C is more work than just doing it in Lua.

  -spc