lua-users home
lua-l archive

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

2015-10-12 13:08 GMT+01:00 <>:
> I'm still evaluating how to expose my pascal
> tables to lua scripts.
> So far, I understand that I have to use
> metatables linked to a table or to userdata. On the argument the manual
> is a bit ambiguous; it says "Tables and full userdata have individual
> metatables [other types share a metatable per type]". If all light
> userdata share the same metatable, I could have problems in the future.

Yes, that's why you shouldn't use a light userdata to wrap your tables.

> Moreover, I am not sure that lua scripts can "subscript" a light
> userdata the same way as a table.

I believe it can. You just need to define a __index in the light
userdata metatable. Then all light userdata can be indexed. But as
there's only a single metatable for all light userdata this is not a
good solution in general (because other binary modules might use light
userdata differently).

> [...]
> Rena offered 4 ways.
> (1
> Store the table name in the metatable). Nice and straightforward, I
> have to think about it.

This means you need to have one metatable per table. This is overkill.

> (2 Map a value->tablename in the registry).
> Doesn't work if it is true that reference to a table can become
> invalid.

Lua references cannot become invalid. It's only C pointers to these
values that can become invalid. So this works fine.

> (3 Keep the name in an upvalue). I've still to understand
> what an upvalue is. If upvalues are contexts for closures, then it is
> another nice solution to think about.

This means having a different __index function for each Pascal table,
which means a different metatable. Again this is overkill.

> (4 Use userdata instead). I must
> investigate userdata, I suspect that they are not perfect for what I
> want. It was subtle the mention to C switch statement, as Boris also
> did. I will have no more than 8-9 tables, so any switch statement is
> faster than a lookup in a lua table.

Userdata are actually perfect for what you want to do. You don't need
any of the table features. What you want is a generic Lua object that
represent your Pascal table, and full userdata are designed for that.
You can override all behaviours of the object when accessed from Lua
with the metatable. And inside the userdata block of memory you can
store any information you want for your native code (for example the
name of the Pascal table, or a pointer to it).

>From what I've read of your problem I don't see any reason not to use
full userdata to represent your objects.