Diberdayakan oleh Blogger.

Senin, 10 Maret 2014

How to include function in lua file from another lua file

by Joielechong sipayung  |  in pemrograman at  Senin, Maret 10, 2014

Detail of lua can be read here

There  are 2 ways to include function from lua file to another lua file.
To explain the ways, we will use this schema:
 there must be at least 2 file, here we use
 1. caller.lua  ; lua file from where we call other file function.
 2. called.lua ; file where called function reside.

here the code for caller.lua:

function main()
   print("main called")
end

main()


Here the code for called.lua:
function called()
   print("i am called")
end


The Ways
A. First way, Using require
By using require, our called file must be resided in the same path with the caller file. If the called file not in the same path, lua will throwing some error. If we want the called file work, we must place the called file in lua library path. There is nothing needed to change in called.lua. We only need to change called.lua.

Here the code for caller.lua
require "called"
function main()
   print("main")
   called()
end


B. Second way, Using dofile
dofile working like require with exception that we need to use the full path of the called file. The benefit of using loadfile is we can call called file from another directory of the caller file. There is nothing needed to change in called.lua. We only need to change called.lua.

Here the code for caller.lua
require "PATH_OF_CALLED_FILE/called.lua"
function main()
   print("main")
   called()
end

PATH_OF_CALLED_FILE is the path of the called.lua


For detail of using require and dofile, please with http://www.lua.org/

0 comments:

Silahkan tinggalkan komentar anda: