Calling Functions Lua - lua

My problem is that I have a function that needs to be called before it is referenced. Another words, the code looks like:
doStuff()
local function doStuff() end
and whenever I try to run it, it cannot reference the function doStuff(). My question is how can I call this function without moving the function above where it is called? So I don't want:
local function doStuff() end
doStuff()
since it will cause errors in other parts of my program.

a function that needs to be called before it is referenced
You cannot. You need to solve this problem in a different way. The only situation you may need to do that is if you have two functions that recursively call each other. You can do this way:
local a
local function b()
a()
end
a = function()
b()
end
a()
This will go into infinite recursion, but you should get the idea. Another option is to use global variables, but you still won't be able to call a function before it's defined (by any means).

Related

How can I get the parameters of a function from a function passed as a parameter to my function, in Lua?

I'm trying to decorate multiple functions with a function decorator, and I want to get the parameters of a function that I'm gonna decorate (in this case called fun in the parameters) and I want to pass as an argument to the returned function (in this case called func) the arguments of the gotten function from the parameters (which is called fun)
So it may look like this:
local function decorator(fun)
local function func(fun.args)
-- Write here custom behaviour to add to the function 'fun'
fun(fun.args)
end
return func
end
However, obviously there is no such thing as fun.args that was just a way of explaining with more exactitude to you what I want. Take in mind this, I DON'T know the function I want to decorate, and the functions I want to decorate may be different to each other, so this would be a way of ADDING a custom behaviour to a function (as you can see in the code example above)
So, is there a way to do what I'm needing?
Lua supports varargs via .... In your case, you'd use it like this:
local function decorator(fun)
local function func(...)
-- Write here custom behaviour to add to the function 'fun'
fun(...)
end
return func
end
And if you want to use the arguments in the "custom behaviour" section, then you can do local args = {...}, and then access them numerically (e.g., args[1] would contain the first argument).

function of a required file in lua doesn't seem to be called

I am trying to use require keyword in LUA to include a file with functions, since I am new to LUA firstly I tried a simple print function:
globalfunctions.lua
local globalfunctions = {}
function printSomething()
print("OOOK")
end
return globalfunctions
then I tried to call this function writing:
local m = require "globalfunctions"
m.printSomething()
but an error occurred saying "attempt to call field printSomething (nil value)"
What I am doing wrong?
The problem is you declare a function but don't add it to your module.
To actually store the function in the module returned by require, you need to add it to the table you return at the end of your module.
globalfunctions.printSomething = printSomething
Note that globalfunctions is a deceiving name choice, since a) it's a local variable itself b) the functions it will contain will not be global either, they are contained by your module
Secondly: Ideally, to make your module behave as most people expect it, you would make the function local as to not pollute the global namespace (potentially overriding an existing variable).
You made global functions a local value, meaning it can only operate locally, try changing local to global.

Can I inject a function into a Lua function?

So if I have this lua function
function dostuff(x)
function foo () x=x+1; end
foo();
return x;
end
And it turns out i need foo many times. But it is mainly useful because it has access to the x upvalue. Is there a way to pull foo out of dostuff, but still have it access to x?
I tried to put foo() global and adding it to dostuff, like this:
function foo () x=x+1; end
function dostuff(x)
foo();
return x;
end
dostuff.foo = foo
Which does not work as in lua functions are distinct from tables (unlike js).
I still have a feeling that this does work in lua, probably using metatables. But I just not know enough about it yet. I know a lot of ways to avoid this and work around it. I am just curious if there is a way to do it.
Maybe another way to look at is, can you call a global function with a choice of closure?
A cleaner and clearer way would be to just pass arguments to foo, which I would recommend.
Another would be to use global variables, or variables local to some chunk (i.e. module or block), common to all related functions.
Otherwise, I didn't find any way to do this. I would suggest redesigning your approach.
What you want is dynamic scoping. Unfortunately Lua doesn't have dynamic scoping. It has lexical scoping. In JavaScript you may simulate dynamic scoping using eval, but Lua doesn't have eval.
As a last resort you could use inheritance. The way I usually do inheritance in Lua is using an extend function, which is similar to the Object.create function in JavaScript:
local o = {}
function o:extend(table)
return setmetatable(table, {
__index = self
})
end
Using this method I can now create an object which will be used for dynamic scoping:
local dynamic = o:extend {}
function dynamic:foo()
self.x = self.x + 1
end
The method foo is dynamic in the sense that it's variable x doesn't point to any specific value. It depends on the value of self which can be changed. We use it as follows:
function dostuff(x)
local scope = dynamic:extend {
x = x
}
scope:foo()
return scope.x
end
However instead of creating a new scope every time you execute dostuff it would be better to simply do:
local myscope = dynamic:extend {}
function myscope:dostuff(x)
self.x = x
self:foo()
return self.x
end
In fact if you decide to refactor your code as shown above then you don't even need inheritance. All you need to do is:
local myscope = {}
function myscope:foo()
self.x = self.x + 1
end
function myscope:dostuff(x)
self.x = x
self:foo()
return self.x
end
The only difference is that now you would have to call myscope:dostuff instead of calling dostuff directly. This is however a good thing as you don't pollute the global scope.
This is the way I would do it, and this is the way I would recommend that you do it as well. All the Lua standard library functions are also defined on objects.
Since you gave only a crude example of what you wanted to do and not your actual use case, suggesting an alternative is a bit hard. To start off, to me this is what it sounds like you want
local x;
function foo() x=x+1 end
function dostuff(a)
x = a;
foo();
return x;
end
My problem here is that foo is so simple and there is absolutely no reason to not make it a function that takes a value x and returns x+1. Further, while the necessary initialisation step for x is not really bad and should not result in any bugs right away, it will make development a bit odd when you have to remember to initialize variables for another function and may create a debugging hell if you don't.
So, since Lua also supports multiple return values, the code above is actually a bad idea that gives you no benefit over something like:
function foo(a,b,c) return a,b,c end
function dostuff()
a,b,c = foo(a,b,c);
end
Since you wrote about code re-use, here is a general ... nudge to what else you can do, which is making use of closures.
You can turn your structure around and make not foo take x as an argument, but have dostuff take foo as an argument:
function dostuff(foo)
return foo()
end
dostuff(function() return 1 end)
dostuff(function() return 2 end)
Taking this a step further brings you to a technique called partial application.
function dostuff(foo)
return function(x)
return foo(x);
end
end
dostuff(function(x) return x+1 end)(17)
local f = dostuff(function(x) return x+1 end)
f(17)f(18)f(19) -- ...
Now that means you can not only modify the way your function works inside from the outside, but you can save that state too. As an added bonus you can also put expensive operations, that you only have to do once per "instance", in the outer function and save some performance.
I hope these are enough ideas to help you with your code re-use issues ;)

Declaring Lua Functions and referencing with correct name

What is the difference between the following Lua scripts in terms of function scope. How would it effect the need to require 'calculator' in some other Lua script. And how would it be referenced in say a LuaState.getGlobal(function_name). What would be its proper function name? Also any comment on advantages/disadvantages of the declaration approaches.
A) Calculator.lua
function foo(n)
return n+1;
end
B) Calculator.lua
calc= {}
function calc.foo(n)
return n+1;
end
C) Calculator.lua
function foo(n)
return n+1;
end
function calculator()
calc = {}
calc.foo=foo
return calc
end
I don't know what it is you mean exactly by the "scope" of these scripts. Exactly what these scripts do depends on how they're being executed. You could give them a different environment, thus changing what they think of as "globals".
So, I will explain what each of these scripts does based on the assumption that you are loading them with dofile, dostring, or something of the like. That is, you're applying them to the global environment.
A)
This creates a single global variable, foo, which is a function.
B)
This creates a single global variable, calc, which is a table. This table has a single entry, with the key foo, who's value is a function.
C)
This creates two global variables. foo is a function. calculator is also a function. Each call to calculator will cause the global variable calc to be overwritten. The new value of calc will be a table that has a single entry, with the key foo, who's value is a copy of what is stored in the global variable foo.
It's hard to say what the "advantages" of method C are, since it makes no sense. It creates two functions instead of one, and that second function keeps creating new tables.
B is just a "namespace" scoped version of A. The general expectation with Lua modules is that including them will usually create some table that will contain all of the functions in that module, to avoid name conflicts with existing global state. In that regard, B may be better. But it depends mostly on what this script will be used for.
Personally, for simple shell scripts and utility scripts, I don't bother with proper module scoping. When I do make a proper module, I generally use the module Lua function.
Not exactly an answer, but a comment on semantics - in Lua, you do not declare a function, you create it. The function becomes available at the time the function(...) ... end is executed. How it is available depends on where you store it.
You have to remember that:
function myfun(foo) print('foo') end
is just syntactic sugar for:
myfun = function(foo) print('foo') end
If you do not do anything special, myfun becomes a global variable stored in the global state (accessible through _G). If you say local myfun before actually calling function myfun() end, the function (actually a closure) will be stored in the local variable and available only to the scope of the local variable.
If you use require, it just finds the file and loads it once. It doesn't do anything fancy with the module like hiding globals, etc. So if you write function foo() end in your module Calculator.lua, then calling require 'Calculator' will create a function in global foo, which you can access using LuaState.getGlobal("foo"). If you create a table of functions (step B), you have to use 2 steps:
L.getGlobal("calc") -- pushes the "calc" global (a table) to the stack
L.getField(-1, "foo") -- gets the "foo" field from the table

Lua MiddleClass. How to pass "self" from another file

Say, If i have two or more files using the middleclass extension more or less like this. I omitted some of the obvious middleclass implementation code.
File A:
function Battlefield:initialize()
self.varA
self.varB
end
function Battlefield:attack()
--I want to use self.varA here
end
File B
BattlefieldInstance = Battlefield:new()
function doStuff()
BattlefieldInstance:attack()
end
I know this structure more or less works because i already use it plenty on my project, but my problem is that i want to use these self variables. Normally a self instance is passed between functions inside the same file to do this, but when i do it from another file i obviously can't pass self, because it would be another self, and i need the self from the file where the function is located. Sorry if my question is a bit confusing. I'll try and clarify any questions there are.
I have no idea what middleclass is, but I think you're confusing yourself. The way self works in Lua is a function that looks like function Battlefield:attack() is absolutely the same thing as function Battlefield.attack(self). In other words, self is just an implicit first parameter to the function. And a method call instance:attack() is exactly equivalent to instance.attack(instance) (though it won't evaluate instance twice if you use an expression there).
In other words, BattlefieldInstance:attack() should do exactly what you want.
'self' is a keyword that means 'the current object'. So in the case of Battlefield functions, 'self.varA' inside the function is the same variable as 'Battlefield.varA' outside the function.
Middle Class was a lib that I first saw developed for Love2D; I assuming its the same one that corona is using? (I've used Corona a fair bit... but not Middle Class's OOP system)
either way you can also try using meta tables directly, as so:
---FILE A---
Battlefield= {}
Battlefield.__index = Battlefield
function Battlefield:new()
return setmetatable({var1 = 'somedata', var2 = 'somemodata', var3 = 'lotsodata'}, Battlefield)
end
function Battlefield:attack()
print(self.var1)
end
---FILE B---
BattlefieldInstance = Battlefield:new( )
function doStuff()
BattlefieldInstance:attack()
end
and that'll print out self.var1 (somedata).
Hope this helps!

Resources