Page 1 of 1

[0.17.x][scenario] Extend LuaPlayer instance

Posted: Wed Jul 17, 2019 6:24 pm
by cogito123
Hi,

I got for example:

Code: Select all

local p = game.players[1]
Now, I can access properties such as 'force', 'name' and so on. My question is, why I can't assign more properties into this instance? I would like to do something like:

Code: Select all

local p = game.players[1]
p["my_local_variable"] = 123
If my understanding is correct, this syntax is legal in Lua and I should be able to access this field as such:

Code: Select all

game.players[1].print(p.my_local_variable)
This would help me save lines of code and lower the complexity, since I wouldn't be required to use external tables to keep state of players. Why isn't this possible?

Re: [0.17.x][scenario] Extend LuaPlayer instance

Posted: Wed Jul 17, 2019 6:48 pm
by slippycheeze
cogito123 wrote: Wed Jul 17, 2019 6:24 pm Now, I can access properties such as 'force', 'name' and so on. My question is, why I can't assign more properties into this instance?

If my understanding is correct, this syntax is legal in Lua and I should be able to access this field as such:

[...]

This would help me save lines of code and lower the complexity, since I wouldn't be required to use external tables to keep state of players. Why isn't this possible?
Because those objects are not actually Lua objects, they are C++ objects exposed to the Lua engine. There are many things that are special about them, and this is one of them. Just store you data in a table indexed by the unique ID of the object - not the object itself - and accept the limitation.

Re: [0.17.x][scenario] Extend LuaPlayer instance

Posted: Wed Jul 17, 2019 7:01 pm
by eradicator
For players i've done some experiemetns with metatables

Very basic example (DO NOT USE, WILL DESYNC):

Code: Select all

local p = setmetatable({},{__index=game.player})
But i've given up on it as the benefits aren't that great, and it's annoying to handle and causes extra table lookups in most cases (i.e. is minimally slower). You have to store player related data in global anyway, but the player wrapper object can be recreated at any time as long as you know the player_index.

DL;TR: Many things in the api are not LuaTable but LuaCustomTable.