Lua: Basic OO
Lua |
---|
Basics |
Intermediate |
Advanced |
|
XLua |
Add to this template |
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 string.case(str), 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.
string.case = 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'
else
casestr = 'n/a'
end
table.insert(casetable, casestr)
end
return casetable
end
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