Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua, Require, Available Functions

Tags:

require

lua

If I require three included files in my Lua script, can any function in any one of those files then see (and most importantly, call) any of the other functions ?

I'm running into the problem of functions calling functions which call other functions. I tried to put the various functions in other files, and then include them instead of writing them into the main file.

I think it's working, my tests are convincing if not conclusive.

My mainline code does this...

 require "SOME_REQUIRED_FILE_01"
 require "SOME_REQUIRED_FILE_02"
 require "SOME_REQUIRED_FILE_03"

 XYZ = 0

 File_02_Function_A()

I looked on The Lua Site and found THIS PAGE but I'm not totally clear on it.

Can EVERY function in all three required files see EVERY OTHER function in all three files ?

like image 765
User.1 Avatar asked Apr 25 '14 18:04

User.1


People also ask

What is %f Lua?

In Lua, the following are the available string formatting syntax or string literals for different datatypes: %s : This serves as a placeholder for string values in a formatted string. %d : This will stand in for integer numbers. %f : This is the string literal for float values.

Does Lua support OOP?

OOP in LuaYou can implement object orientation in Lua with the help of tables and first class functions of Lua. By placing functions and related data into a table, an object is formed.

Can you call a function within a function Lua?

Calling a function from within itself is called recursion and the simple answer is, yes.

How do I create a global variable in Lua?

The syntax for declaring a global variable in Lua is pretty straightforward, just declare whatever name you want to use for your variable and assign a value to it. It should be noted that we cannot declare a global variable without assigning any value to it, as it is not something that Lua allows us to do.


1 Answers

require is basically the same as dofile, except for mechanisms that avoid loading the same file multiple times (and some other useful things like loaders). That means, that they can set global variables (though they should not) as well. So, if you set a global variable in one of the required files, the global can be seen in the entire scope of the require function. That means in other required files as well.

Having said that, it is not best practise to set global variables in required files. It is better to return a table that has functions and variables exported by the module inside. Then you would call those functions like this:

local some_required_file_01 = require "SOME_REQUIRED_FILE_01"
local some_result_01 = some_required_file_01.some_function_01()
like image 106
W.B. Avatar answered Oct 18 '22 18:10

W.B.