[Lua Tip] Imitate enum with a few lines of code


In my opinion, using string literals in code is a habit you better avoid, so here is a simple function to create a constTable - a table that returns given key ((or something based on given key) when indexed. This way you can avoid using string literals and improve readability and refactorability - it's easier to group values semantically this way and find (and replace) in files.

function createConstTable(generator)
    generator = generator or function(x) return x end
    return setmetatable({}, {__index = function(t,key) return generator(key) end})
end

Usage:

luaTypes = createConstTable()
if type(someVariable) == luaTypes.number then -- better than just "number"!
    doSomethingWithNumber()
end

Leave a comment

Log in with itch.io to leave a comment.