So today when I sit to brush up my lua skill, suddenly one thing come to my mind, I wish if some library like underscore.js also there for lua, and I started googling and instantly my wish get fulfilled. I found the same “underscore.lua” here. Although it is there for long time back I found it very much useful so I thought to share it with you all folks. I wish it will be helpful for all newbies.
Description : So today I am going to explain you the easy way to use it in your code following with few examples.
Before starting let me explain what is this underscore.lua is for. It is nothing but a library which provides you few utilities, methods using which with one line you may do the job whereas without it you may need to write few more lines to perform the same job.
For example, there may two different table containing different data and you need to merge it into a single table. For that underscore provides a function called “extend” where you need to pass two different table and it will give you a single merged table. Isn’t it interesting. There are so many others functions like this which may reduce your code complexity.
To take the advantage of this library you just need to get the code for this library from here and save it to your root directory along with your “main.lua” file. This much only.
FOLDER STRUCTURE :
TestProject (Root folder)
Now its usage. Let me take a simple example to explain the same. All we know about for loop. Where we need to initialize a counter from where the loop gets started, a final count up to which loop will be move and a loop increment and decrement process. Whereas the same can be done here with “each” function which will only need the list containing data upon which loop will be done. It will automatically goes for each and every instance of the list item.
CODE BLOCK :
-- Define underscore library with requiring it
local _ = require( "underscore" )
-- Callback function which will be operated for each loop
local function printInstances( item )
-- Print item
print( "---------- : ".. item )
-- Now the magical function
Above code will call “printInstances” function for each item passed in “each” function and it will print them one after another.
Summary : So here we learned about a new utility library for lua and its installation process along with example. Hope it will be helpful for freshers.