Answers for "unpack lua"

Lua
0

unpack lua

A special function with multiple returns is unpack. It receives an array and returns as results all elements from the array, starting from index 1:

    print(unpack{10,20,30})    --> 10   20   30
    a,b = unpack{10,20,30}     -- a=10, b=20, 30 is discarded
An important use for unpack is in a generic call mechanism. A generic call mechanism allows you to call any function, with any arguments, dynamically. In ANSI C, for instance, there is no way to do that. You can declare a function that receives a variable number of arguments (with stdarg.h) and you can call a variable function, using pointers to functions. However, you cannot call a function with a variable number of arguments: Each call you write in C has a fixed number of arguments and each argument has a fixed type. In Lua, if you want to call a variable function f with variable arguments in an array a, you simply write

    f(unpack(a))
The call to unpack returns all values in a, which become the arguments to f. For instance, if we execute
    f = string.find
    a = {"hello", "ll"}
then the call f(unpack(a)) returns 3 and 4, exactly the same as the static call string.find("hello", "ll").
Although the predefined unpack is written in C, we could write it also in Lua, using recursion:

    function unpack (t, i)
      i = i or 1
      if t[i] ~= nil then
        return t[i], unpack(t, i + 1)
      end
    end
The first time we call it, with a single argument, i gets 1. Then the function returns t[1] followed by all results from unpack(t, 2), which in turn returns t[2] followed by all results from unpack(t, 3), and so on, until the last non-nil element.
Posted by: Guest on September-14-2021

Browse Popular Code Answers by Language