I am trying to do an sort of switch case script. My problem is that i am not able to pass parameters to the functions.
function zerozero(input)
return input
end
function zeroone(input)
return input
end
function onezero(input)
return input
end
function oneone(input)
return input
end
local switch = {
['00'] = zerozero(input),
['01'] = zeroone(input),
['10'] = onezero(input),
['11'] = oneone(input)
}
local first_2_bits = "00"
local input = "test"
local x = switch[first_2_bits](input)
print("x: ", x)
If i am trying to compile this, an error occurs. The problem is that it is not able in this way to pass the input parameter to the function zerozero. Do you know how i am able to pass parameters to the functions ? Thanks alot!
CodePudding user response:
I found the solution: Just make sure that you do not have the parmeters inside the table. The table should look like this:
local switch = {
['00'] = zerozero,
['01'] = zeroone,
['10'] = onezero,
['11'] = oneone
}
CodePudding user response:
function zerozero(input)
return input
end
function zeroone(input)
return input
end
function onezero(input)
return input
end
function oneone(input)
return input
end
Given those functions
local switch = {
['00'] = zerozero(input),
['01'] = zeroone(input),
['10'] = onezero(input),
['11'] = oneone(input)
}
is equivalent to
local switch = {
['00'] = input,
['01'] = input,
['10'] = input,
['11'] = input
}
So switch['00'] resolves to input which in your case is a string.
A string cannot be called unless you defined a __call metamethod for strings.
Note the difference between a function value and a function call. In your case the table constructor will evaluate each function call once and store its return value in the table field.
