+ Reply to Thread
Results 1 to 3 of 3

Thread: Variable Arguments using Lua Function unpack

  1. #1
    Shadowlander
    Join Date
    Jun 2011
    Posts
    30

    Default Variable Arguments using Lua Function unpack

    Has anyone had any problems using the standard Lua function unpack()? I believe the problem is coming into play with the hidden variable arg not actually being available for use.

    Code:
    function foo(x, ... )
        local y, z = unpack(arg)
        print(type(x))  --  expect to print string
        print(type(y))  --  expect to print number
        print(type(z))  --  expect to print nil
    end
    
    function main()
        foo("Apple", 1)
    end
    The line where unpack(arg) is executed, an error is thrown: "bad argument #1 to 'unpack' (table expected, got nil)". I've checked arg, and sure enough it is nil.

    Reading through the Programming in Lua documentation, and everything looks correct me.

  2. #2
    Plane Walker Kreiri's Avatar
    Join Date
    Feb 2011
    Posts
    402

    Default

    Wasn't magic arg table deprecated in Lua 5.1?
    (Edit: Your link says it right on top of the page: "This first edition was written for Lua 5.0. While still largely relevant for Lua 5.1, there are some differences.")

    1. If you want to use unpack, use ... instead of arg and make it a table before unpacking:

    Code:
    function foo(x, ... )
        local y, z = unpack({...})
        print(type(x))  --  expect to print string
        print(type(y))  --  expect to print number
        print(type(z))  --  expect to print nil
    end
    
    
    foo("Apple", 1)
    Result (using http://www.lua.org/cgi-bin/demo):
    string
    number
    nil
    2. Or add local arg={...} to your code:

    Code:
    function foo(x, ... )
        local arg = {...}
        local y, z = unpack(arg)
        print(type(x))  --  expect to print string
        print(type(y))  --  expect to print number
        print(type(z))  --  expect to print nil
    end
    
    foo("Apple", 1)
    3. (Edited 'cause I was half asleep and gave wrong answer)

    Just use y, z = ...
    Code:
    function foo(x, ... )
        local y, z = ...
        print(type(x))  --  expect to print string
        print(type(y))  --  expect to print number
        print(type(z))  --  expect to print nil
    end
    
    foo("Apple", 1)
    Last edited by Kreiri; 02-16-2012 at 01:43 AM.
    Feminism is the radical notion that women are people.

  3. #3
    Shadowlander
    Join Date
    Jun 2011
    Posts
    30

    Default

    Works great now! Thanks a bunch. Didn't even think to look at if it changed from version to version.

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts