How much do I use these tables in lua?

So I am writing some Lua and when using tables I wanted to do something similar to "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 am doing, but is it okay to access such information? Or is there a more efficient way?

+3


source to share


1 answer


When talking about efficiency, you need to distinguish between maintenance and code performance. In Lua, as in most languages, the two points diverge.

It's easy to always use pairs

instead of ipairs

, add items to a table table.insert

, concatenate rows ..

, etc. BUT that is not the way of a fast running program.

One document each Lua programmer had to read: "Recommendations for improving Lua" by Roberto Jerusalem



To your code:

  • Don't use table.insert

    , control table size and inserts yourself.
  • The table only has array entries, so use ipairs

    .
  • Avoid useless variables, construct them as far as possible ( newPlayer

    ).
  • Use _

    ( k

    ) as placeholders for unused variable names .

There are some other rules for LuaJIT due to massive optimizations by part of the compiler, i.e. (i)pairs

slows down much less.

+2


source







All Articles