“main” function in Lua?

There’s no “proper” way to do this, since Lua doesn’t really distinguish code by where it came from, they are all just functions. That said, this at least seems to work in Lua 5.1: matthew@silver:~$ cat hybrid.lua if pcall(getfenv, 4) then print(“Library”) else print(“Main file”) end matthew@silver:~$ lua hybrid.lua Main file matthew@silver:~$ lua -lhybrid Library … Read more

Sort a Table[] in Lua

A table in Lua is a set of key-value mappings with unique keys. The pairs are stored in arbitrary order and therefore the table is not sorted in any way. What you can do is iterate over the table in some order. The basic pairs gives you no guarantee of the order in which the … Read more

Get back the output of os.execute in Lua

If you have io.popen, then this is what I use: function os.capture(cmd, raw) local f = assert(io.popen(cmd, ‘r’)) local s = assert(f:read(‘*a’)) f:close() if raw then return s end s = string.gsub(s, ‘^%s+’, ”) s = string.gsub(s, ‘%s+$’, ”) s = string.gsub(s, ‘[\n\r]+’, ‘ ‘) return s end If you don’t have io.popen, then presumably … Read more

How can I embed Lua in Java?

LuaJ is easy to embed in Java. I did have to change a few lines of their source to get it to work how I expected (it didn’t require the IO library automatically). http://sourceforge.net/projects/luaj/

Lua find a key from a value

If you find yourself needing to get the key from the value of a table, consider inverting the table as in function table_invert(t) local s={} for k,v in pairs(t) do s[v]=k end return s end

How to fix “NSURLErrorDomain error code -999” in iOS

The error has been documented on the Mac Developer Library(iOS docs) The concerned segment from the documentation will be: URL Loading System Error Codes These values are returned as the error code property of an NSError object with the domain “NSURLErrorDomain”. enum { NSURLErrorUnknown = -1, NSURLErrorCancelled = -999, NSURLErrorBadURL = -1000, NSURLErrorTimedOut = -1001, … Read more

Lua pattern matching vs. regular expressions

Are any common samples where lua pattern matching is “better” compared to regular expression? It is not so much particular examples as that Lua patterns have a higher signal-to-noise ratio than POSIX regular expressions. It is the overall design that is often preferable, not particular examples. Here are some factors that contribute to the good … 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