Enumeration (enum in lua) .Want to use enum in lua5.2.4
Asked Answered
F

3

14

I have a condition where in my lua script I want to use enum like for SUCCESS I can give 1 and for FAILURE I can give 0 I am using lua version 5.2.4 Can anyone please help me on how to use enum I want to use enum

elseif(cc_config_cmd == "DELETE" and file_found==1)then
            api:executeString("callcenter_config queue unload " .. queue_name)
            stream:write("1")
else
            stream:write("0")

end
Firewood answered 30/12, 2021 at 8:50 Comment(0)
P
28

There are no enums in Lua.

Simply define variables.

SUCCESS = "1"
FAILURE = "0"

stream:write(SUCCESS)

Or put it into a table which would be quite similar to enum style syntax.

Result = {SUCCESS = "1", FAILURE = "0"}
stream:write(Result.SUCCESS)
Potheen answered 30/12, 2021 at 9:4 Comment(1)
Upvoting this for the "put your enum values in a table" recommendation!Judejudea
C
6

Lua does not have native support for "enums", but they are quite easy to emulate.

Naively, they can be implemented as a table that contains unique values for each key. While strings or numbers suffice, I find that simply using empty tables work best:

local Result = { 
   Success = {},
   Failure = {},
}

Since Lua's comparison operator (==) for table check if the two sides are the same object, not if they have the same fields, Result.Sucess ~= Result.Failure. This is more efficient than comparing two strings and saves the developer from the hassle of picking a unique value for each field.

In a unityped languages such as Lua, a record of unique values acts pretty much as an enum in other languages.

If the syntax is too alien for you, this mechanism can be easily automated:

local enum = function(keys)
    local Enum = {}
    for _, value in ipairs(keys) do
        Enum[value] = {} 
    end
    return Enum
end

local Result = enum { "Success", "Failure" }
assert(Result.Success == Result.Success)
assert(Result.Failure == Result.Failure)
assert(Result.Success ~= Result.Failure)
Chesson answered 25/9, 2023 at 8:23 Comment(0)
G
1

As far as I know, there is no enums in Lua, you can use strings such as your current code. The strings will be interned inside the Lua Virtual Machine, so in the memory the strings will not be duplicated.

Another option will be to use numbers in place of strings.

local COMMAND_DELETE = 1
local COMMAND_TEST_1 = 2
local COMMAND_TEST_2 = 3

Other options would be to use a third-party package such as the enum package or maybe go further and use a Lua Preprocessor

Grefer answered 30/12, 2021 at 8:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.