0

I have a problem, i need to call a function with variable parameters that i get from a webservice... so for example:

I have a function:

function MyPrint(param1, param2)
   print(param1, param2)
end

I save this function in an array of callbacks:

callback[1] = MyPrint

I get parameters from server:

params = "[2, 88]" --> JSON from server

I do:

params = json.decode(params)
-- so 
-- params[1] = 2
-- params[2] = 88

I tried to pass this parameters to my callback as:

pcall(callback[1], unpack(params))

I got 2 and 88 on MyPrint function...

But if server sends "[null, 88]", I got nil on both values... I have readed that unpack function has problem with null values... but then... how can I call callback[1] with some null values?

Is there a way to pass an array of parameters directly to function without unpack it?

EDIT: I created MyPrint as an example... but really I don't know how many params needs the callback function, i only have a list of functions and needs to call them with a variable number of parameters that i got from server.

5
  • pastebin.com/10UuPc6j -- works here. What's your lua version? What's the value of params before unpacking? Also, see here Commented May 28, 2015 at 22:58
  • 1
    json.decode should create additional field n in the table returned to store the number of arguments. Then your_function(unpack(params,1,params.n)) would solve the problem. Commented May 29, 2015 at 4:53
  • @EgorSkriptunoff There is no "n" field... print(params.n) --> nil Commented May 29, 2015 at 12:51
  • @diego It seems the problem is on json.decode ignoring the null parameter thats why your example works... it pass the null directly without parsing the null with json.decode Commented May 29, 2015 at 12:53
  • If you can't make json.decode create a n field or equivalent then there is a loss of data. You can't very well deal of a json object without know how many elements there are. To move on, you'll have to find a way to carry over the number of elements. Commented May 30, 2015 at 14:45

1 Answer 1

1

If a table has gaps, you should explicitly specify a range of indices to unpack: table.unpack(params, 1, table.maxn(params)). This works well in lua 5.1.5.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.