lua-users home
lua-l archive

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


Thatcher Ulrich wrote:
> 
> Maybe I'm misunderstanding something, but it seems as though Lua must
> maintain a symbol table internally that maps identifiers to integers or
> pointers, for use in indexing tables and referring to global variables in
> compiled code and so on.

Right.  Lua does it by using unique strings: each string exists only
once.  So, two strings are equal if their (struct TString) pointers
are equal.  The pointers you get with lua_tostring are at a fixed offset
from struct TString so they share the same property.

There's only one thing to note: if a string is no longer used by Lua
it may be garbage collected and the memory (and thus the pointer) may
later be reused by another different string.  So if you want the pointer
to stay the same even if it's temporarily not used by Lua you should
make sure that you keep a reference.  That can be done either by calling
lua_ref(L, 1) or by putting the string into some Lua data structure
(table, function upvalue) that will not be collected.

Ehem... another note: this property of string pointers is afaik not
documented.

> Essentially what I want is something like:
> 
> int     get_symbol_id( const char* name );
> const char*     get_symbol_name( int id );
> void    lua_getglobal_using_id( lua_State* L, int id );
> etc.

This can be even done without knowing about the above mentioned
property of string pointers.  Use lua_ref/getref to map strings
to integers.  If you call get_symbol_id more then once for a given
name you have to manage a lookup table though to not create
multiple references for the same name.

Ciao, ET.