4

So I've been scripting some Lua and when using tables I wanted to make something similar to a "node" or "class"

local playerInfo = {} 
if player then
    local newPlayer = {NAME = name, HP = 10, DMG = 4}
    table.insert(playerInfo, newPlayer) 
end

for k, v in pairs(playerInfo) do
    print(v.NAME) 
end

This is just an example of what I'm doing, but is it OK to access information like this? Or is there a more efficient way?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
krazyito65
  • 95
  • 1
  • 1
  • 9

1 Answers1

4

When talking about efficiency one has to differ between code maintenance and performance. In Lua, like in most languages, these two points go apart.

It's easy always to use pairs instead of ipairs, append elements to table by table.insert, concatenate strings by .., etc. BUT that's not the way for a fast running program.

One document every Lua programmer should have read: Lua Performance Tips by Roberto Ierusalimschy

To your code:

  • Don't use table.insert, manage table size & insertions by yourself.
  • Your table has just array entries, so use ipairs instead.
  • Avoid useless variables, construct in-place as far as possible (newPlayer).
  • Use _ as placeholder for unused variable names (k).

For LuaJIT there're some other rules because of massive optimizations by the compiler part, f.e. (i)pairs is there much less a slow-down.

Youka
  • 2,646
  • 21
  • 33
  • Thanks for the input. When you say 'useless' variables, you mean to just do something like `table.insert(playerInfo, {NAME = name, HP = 10, DMG = 4})` instead? I will remember to use `_` as well. There are some loops where I actually use `k` but that makes sense. and for `table.insert` how would I manage the size insertion myself if I don't know how many entries into the table I'm going to get? – krazyito65 Aug 08 '15 at 08:31
  • @krazyito65 Yes, i meant that about 'useless' variables. `table.insert` asks for table size which hasn't cost of O(1) (see [implementation](https://github.com/LuaDist/lua/blob/master/src/ltable.c#L560)). Additionally tables can have holes by nil values and table size request considers these holes as end. Storing the table size as field **n** and increment/decrement it by modifications is more work for users but is safer and faster. – Youka Aug 08 '15 at 09:32
  • Using _ for unused variables is a readability-enhancing convention (and code inspection warning inhibitor). In Lua, the only performance gain would be if you used it repeatedly. It's just like any other variable. – Tom Blodget Aug 08 '15 at 23:56