Inline conditions in Lua (a == b ? “yes” : “no”)?
Sure: print(“blah: ” .. (a and “blah” or “nahblah”))
Sure: print(“blah: ” .. (a and “blah” or “nahblah”))
Your code is efficient but wrong. (Consider {[false]=0}.) The correct code is if next(myTable) == nil then — myTable is empty end For maximum efficiency you’ll want to bind next to a local variable, e.g., … local next = next … … if next(…) … (When next is local, the code finds primitive function next … Read more
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
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
First, compute the center point. Then sort the points using whatever sorting algorithm you like, but use special comparison routine to determine whether one point is less than the other. You can check whether one point (a) is to the left or to the right of the other (b) in relation to the center by … Read more
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
In Lua 5.2 the best workaround is to use goto: — prints odd numbers in [|1,10|] for i=1,10 do if i % 2 == 0 then goto continue end print(i) ::continue:: end This is supported in LuaJIT since version 2.0.1
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
The colon is for implementing methods that pass self as the first parameter. So x:bar(3,4)should be the same as x.bar(x,3,4).
You can use awk: awk ‘{ sum += $1 } END { print sum }’ file