Why do Lua arrays(tables) start at 1 instead of 0?

Lua is descended from Sol, a language designed for petroleum engineers with no formal training in computer programming. People not trained in computing think it is damned weird to start counting at zero. By adopting 1-based array and string indexing, the Lua designers avoided confounding the expectations of their first clients and sponsors. Although I … Read more

How to dump a table to console?

If the requirement is “quick and dirty” I’ve found this one useful. Because if the recursion it can print nested tables too. It doesn’t give the prettiest formatting in the output but for such a simple function it’s hard to beat for debugging. function dump(o) if type(o) == ‘table’ then local s=”{ ” for k,v … Read more

How to get number of entries in a Lua table?

You already have the solution in the question — the only way is to iterate the whole table with pairs(..). function tablelength(T) local count = 0 for _ in pairs(T) do count = count + 1 end return count end Also, notice that the “#” operator’s definition is a bit more complicated than that. Let … Read more

Split string in Lua?

Here is my really simple solution. Use the gmatch function to capture strings which contain at least one character of anything other than the desired separator. The separator is **any* whitespace (%s in Lua) by default: function mysplit (inputstr, sep) if sep == nil then sep = “%s” end local t={} for str in string.gmatch(inputstr, … Read more