I would like to declare global metatables in Lua that are registered by a C++ app.
I define the __index metamethod of the metatable and some fields but when the lua script access known fields, the __index is always invoked in my C++ app.
For example I want to register a global table named User which contains three fields : FirstName, LastName and Age.
Here is how I register the table. The table is encapsulated in a class named TLuaStruct that make easier to register table in Lua.
bool TLuaStruct::InternalRegister( std::string tName, bool AddInGC )
{
TLuaStack *ptStack;
TLuaStruct **ptUserLuaStruct;
ptStack = m_ptLua->GetStack();
if( ptStack==NULL )
return false;
// Create a metatable that won't be exposed to Lua scripts.
// The name must be unique
// Stack after the call:
// 1,-1 | table
m_ptLua->NewMetaTable( m_tMetaName );
// Register all of the properties
PushProperties( false, false );
// Register the callback assigned to __index
ptStack->PushCFunction( TLuaStruct_Index_CallBack );
m_ptLua->SetField( -2, "__index" );
// Create a UserData to store the address of this.
// Stack after the call:
// 2,-1 | userdata
// 1,-2 | table
ptUserLuaStruct = ( TLuaStruct** )m_ptLua->NewUserData( sizeof( ptUserLuaStruct ) );
*ptUserLuaStruct = this;
m_pvLuaThisPtr = ( void* )ptUserLuaStruct;
// Switch the userdata and the table
// Stack after the call:
// 2,-1 | table
// 1,-2 | userdata
ptStack->Insert( -2 );
// Associate the metatable to the userdata
// Stack after the call:
// 1,-1 | userdata
m_ptLua->SetMetaTable( -2 );
m_ptLua->SetGlobal( tName.c_str() );
return true;
}
If I assign the metatable itself to __index instead to a C callback, the scripts can access FirstName, LastName and Age in readonly (What I would like to do) but I can't know when the scripts try to access an unknown field cause my C++ app is not invoked.
Maybe Lua always invokes __index when the metatable is userdata so it makes sure the values are up-to-date but it could be nice to defined read-only variable such as function in a table otherwise calling __index all the time can slow down the app.
Is anyone know how to perform this ? Thanks.