I am creating a simple table in Lua that has various functions and an ID field. From Lua script’s perspective, the table looks like this:
ball = entity_query.get_first_entity_by_name(“Ball”);
print(ball.id)
ball.name.set(“new name”)
print(ball.name.get())
The way I do it is this (I have abstraction over it but here is how the non abstracted code looks like):
int getNameFn(lua_State *state) {
lua_getglobal(state, “__privateDatabase”);
auto *pointer = lua_touserdata(state, -1);
auto &entityDatabase = *static_cast<EntityDatabase *>(pointer);
// How do I get this from the table?
uint32_t entity = 10;
const char *name = entityDatabase.getComponent<NameComponent>(entity).name;
lua_pushstring(state, name);
return 1;
}
int setNameFn(lua_State *) {
// First argument passed to this function in Lua
// is at Stack index `1`
const char * argument = lua_tostring(state, 1);
auto *pointer = lua_touserdata(state, -1);
auto &entityDatabase = *static_cast<EntityDatabase *>(pointer);
// How do I get this from the table?
uint32_t entity = 10;
entityDatabase.setComponent<NameComponent>(entity, {argument});
// same type of logic but to set the value
return 0;
}
lua_createtable(state, 0, 2);
// Entity ID is stored in the table
lua_pushinteger(state, entityId);
lua_setfield(state, -2, “id”);
// Copied the ID to the inner table so I can access it
lua_createtable(state, 0, 3);
lua_pushinteger(state, entityId);
lua_setfield(state, -2, “id”);
lua_pushcfunction(state, getNameFn);
lua_setfield(state, -2, “get”);
lua_pushcfunction(state, setNameFn);
lua_setfield(state, -2, “set”);
lua_setfield(state, -2, “name”);
When getNameFn function gets called, I want to read the id field from the table that the function is stored in. Is this possible?
EDIT: Added setter function snippet as well.