Is it possible in LUA to execute a function like foo("param1, param2, param3, param4"), and have it detect it as foo(param2, param2, param3, param4)
Why? I have a scenario where a function can receive as many parameters as I wish, and they can't be sent as a list (It's in CoronaSDK, so I can't really modify the source, and have to adapt to it). So, sometimes I'll have to send 3 parameters, while sometimes I'll be sending 100. Is there anyway of doing this?
they can't be sent as a list (It's in CoronaSDK, so I can't really modify the source, and have to adapt to it)
Sure it can. Watch:
function CallWithParametersInAList(FunctionToCall, paramsInList)
return FunctionToCall(unpack(paramsInList))
end
See? Every array element in paramsInList will be unpacked into arguments to FunctionToCall. Also, every return value from FunctionToCall will be returned.
see
function test(a)
print("this is lua test function."..a);
end
CallWithParametersInAList(test,{33333});
OUTPUT
this is lua test function.33333
You can call a lua function with as many parameters as you want. If the function expects more parameters, they will be set to nil. If the function expects too few parameters, the extra parameters sent will get ignored.
For example:
function f(a, b, c)
print(a, b, c)
end
f(1, 2) -- prints: 1 2 nil
f(1, 2, 3) -- prints: 1 2 3
f(1, 2, 3, 4, 5) -- prints: 1 2 3
edit:
If you must get the parameters from a string and those parameters include things like tables and functions, you have little option but to get the string parsed by loadstring function:
-- s contains the parameters
s = '1,2,{1,2,3}'
-- f is the function you want to call
loadstring('f(' .. s .. ')')() -- prints: 1 2 table: 0061D2E8
I'm not sure about CoronaSDK, but the loadstring function tends to be a bit slow. Try to avoid it if possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With