Lua: Basic OO

From Mario Fan Games Galaxy Wiki
Add to this template
 Standardwikimessagebox.png This article assumes the use of Lua 5.1.

Information may not be accurate or may need revision if you are using a different version.

 Stub.png This article or section is in need of expansion.

Please add further information.

Though Lua has no true class support, it is still possible to emulate object-oriented programming through various methods, usually metatables. Lua uses a special colon syntax to indicate methods, but regular dot syntax can be used instead; however, in the latter case you must remember to include the object to be affected as the first parameter!

Let's say we wanted to check a string for letter case, and return a table containing 'upper', 'lower', or 'n/a' for each character. Additionally, we want to add the function to the basic 'string' library, because it makes sense to do that seeing as it's a string operation. We could always use some function like, which is fine, but we should take advantage of the fact that the 'string' library sets a metatable for strings; this is something Lua assumes we can't do (we can do it but it requires the 'debug' library... not something you want to supply with your program!).

By using colon syntax, we can shorten the original function and make it somewhat more readable. = function (self)
    local casetable = { }
    local casestr = ""
    for chr in self:gmatch("(.)") do
        if select(2, chr:gsub("(%u)", "%1")) == 1 then
            casestr = 'upper'
        elseif select(2, chr:gsub("(%l)", "%1")) == 1 then
            casestr = 'lower'
            casestr = 'n/a'
        table.insert(casetable, casestr)
    return casetable

This can be tested like so:

print(table.concat(("This is a test. ABC 123 !!!"):case(), ", "))

--prints: upper, lower, lower, lower, n/a, lower, lower, n/a, lower, n/a, lower, lower, lower, lower, n/a, n/a, upper, upper, upper, n/a, n/a, n/a, n/a, n/a, n/a, n/a, n/a