The map function is a function that takes two parameters, an array and a function. It takes the array and perform the function on every elements of that array and thereafter returns another array of results gotten from the function's output.
JavaScript and some other programming languages comes with the map function but Lua did not.
So now, we will be creating our own map function in Lua.
local function map(inputArray,inputFunction)
result = {}
for i=1,#inputArray
do
result[i] = inputFunction(inputArray[i])
end
return result
endSo the map function we defined above takes two parameter as you can see inputArray
and inputFunction.
Let's create another function that gets the square of any number...
local function getSquare(num)
return num*num end
Finally, let's test our map function myArray = {1,2,3,4,5,6,7,8,9}
a = map(myArray,getSquare)
do
for int i = 1, #a
print(a[1])
end
The output would be the square of all the number in myArray.
Well guys this marks the end of this blog post, if you have any questions, likes
or dislike please leave a comment below.
Thanks

No comments:
Post a Comment