Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua function call with parameter list in a string

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?

like image 427
Alfredo Gago Avatar asked May 11 '26 14:05

Alfredo Gago


2 Answers

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
like image 179
Nicol Bolas Avatar answered May 14 '26 13:05

Nicol Bolas


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.

like image 22
Ryan Avatar answered May 14 '26 15:05

Ryan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!