-
In my project I have next pattern. local commands = {}
commands["do3"] = function()
print("do3")
end
function commands.do1() print("do1") end
function commands.do2() print("do2") end
function process(cmd)
if cmd then
local command = commands[cmd]
if command then
command()
end
end
end How I can rewrite such code? local commands: {string: function} = {}
commands["do3"] = function()
print("do3")
end
function commands.do1() print("do1") end
function commands.do2() print("do2") end
function process(cmd: string)
if cmd then
local command = commands[cmd]
if command then
command()
end
end
end It has local type Commands = record
do1: function()
do2: function()
do3: function()
end
local type Cmds = enum
"do1"
"do2"
"do3"
end
local commands: Commands = {}
commands["do3"] = function()
print("do3")
end
function commands.do1() print("do1") end
function commands.do2() print("do2") end
function process(cmd: Cmds)
if cmd then
local command: function() = commands[cmd]
if command then
command()
end
end
end It compiles but has more duplication. Also I am embarrassed with types naming for record and enum. What is right approach for such patterns? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
every function that can be executed using that index need to have the same type, so what you can do is something like local type CommandNames = enum
"do1"
"do2"
end
local commands : {CommandNames : function()} = {
do1 = function() print("do1")end,
do2 = function() print("do2")end
}
function process(cmd: CommandNames)
if cmd then
local command: function() = commands[cmd]
if command then
command()
end
end
end Basically, stop using a record and start using a map of commandName : yourFunctionType |
Beta Was this translation helpful? Give feedback.
-
@lenscas's response is correct, this pattern calls for a map, not a record. Which I noticed was the first thing you tried to do, but stumbled into this:
That's a good question. Lua supports different syntaxes for some equivalent operations on tables, because the table type takes on many duties (maps, records, arrays, etc.) — in Teal, I have reserved the The reason is inference: a typical pattern is to do
so Teal infers that Since you have declared in your first attempt that you wanted But a slight variation of your first attempt does, in fact, work: local commands: {string: function} = {}
commands["do3"] = function()
print("do3")
end
commands["do1"] = function()
print("do1")
end
commands["do2"] = function()
print("do2")
end
function process(cmd: string)
if cmd then
local command = commands[cmd]
if command then
command()
end
end
end |
Beta Was this translation helpful? Give feedback.
every function that can be executed using that index need to have the same type, so what you can do is something like
Basically, stop using a record and start using a map of commandName : yourFunctionType