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.

Pipe
  • 2,379
  • 2
  • 19
  • 33
  • http://pastebin.com/10UuPc6j -- works here. What's your lua version? What's the value of `params` before unpacking? Also, see [here](http://stackoverflow.com/questions/1672985/lua-unpack-bug) – Diego May 28 '15 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. – Egor Skriptunoff May 29 '15 at 04:53
  • @EgorSkriptunoff There is no "n" field... `print(params.n)` --> nil – Pipe May 29 '15 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 – Pipe May 29 '15 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. – Tom Blodget May 30 '15 at 14:45

1 Answers1

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.

Alexander Lutsenko
  • 2,130
  • 8
  • 14