[0.17.x][scenario] Extend LuaPlayer instance

Place to get help with not working mods / modding interface.
Post Reply
cogito123
Inserter
Inserter
Posts: 23
Joined: Thu Feb 28, 2019 7:05 pm
Contact:

[0.17.x][scenario] Extend LuaPlayer instance

Post 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?

slippycheeze
Filter Inserter
Filter Inserter
Posts: 587
Joined: Sun Jun 09, 2019 10:40 pm
Contact:

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

Post 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.

User avatar
eradicator
Smart Inserter
Smart Inserter
Posts: 5206
Joined: Tue Jul 12, 2016 9:03 am
Contact:

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

Post 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.
Author of: Belt Planner, Hand Crank Generator, Screenshot Maker, /sudo and more.
Mod support languages: 日本語, Deutsch, English
My code in the post above is dedicated to the public domain under CC0.

Post Reply

Return to “Modding help”