Ryan
Ryan

Reputation: 1

Is this function causing performance issues in Lua?

In Lua, I have a Player metatable:

Player = {}
Player.__index = Player
_players = {}

I create the player object when needed:

function Player:new(id)
    local player = {id = id, name = ...}
    setmetatable(player, self)
    _players[id] = player
    return player
end

Is this function hurting performance by creating new player tables, or simply holding references to the player tables in _players?

function Player:list()
    local player_list = {}
    for _, player in pairs(_players) do
        table.insert(player_list, player)
    end
    return player_list
end

In other words, does copying a table's values (which are tables themselves) into a new table double the memory used? Or is it just a reference?

Upvotes: 0

Views: 70

Answers (1)

Luke100000
Luke100000

Reputation: 1554

https://www.lua.org/manual/5.3/manual.html#2.5.3 Section "2.1 – Values and Types"

Tables, functions, threads, and (full) userdata values are objects: variables do not actually contain these values, only references to them. Assignment, parameter passing, and function returns always manipulate references to such values; these operations do not imply any kind of copy.

Upvotes: 1

Related Questions