select() function in Lua programming

LuaServer Side ProgrammingProgramming

The select function in Lua is used to return the number of arguments that are passed into it as an argument. It can be used in two forms, the first one includes passing an index and then it will return the numbers that are passed after that number into the function as an argument in a list format, the other pattern is if we pass the length operator as a first argument, in that case it simply returns a count of the multiple arguments that are provided.


Let’s explore both the cases in the examples shown below.

Case 1

 Live Demo

print(select(1, "a", "b", "c")) --> a b c
print(select(2, "a", "b", "c")) --> b c
print(select(3, "a", "b", "c")) --> c

In the above example, we have passed an index, and we can see that the output from the select function will be the arguments after the given index.


a   b   c
b   c

Case 2

 Live Demo

print(select("#")) --> 0
print(select("#", {1, 2, 3}))
print(select("#", 1, 2, 3))
print(select("#", {1,2,3}, 4, 5, {6,7,8}))

In the above example, instead of passing an index, I passed the length operator, and hence the output will simply be the number of arguments passed after it.


Published on 19-Jul-2021 12:05:18