Can I inject a function into a Lua function? - lua

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 ;)

Related

Lua - Getting a Localized Variable or Function without using the Debug Library with 2 seperate scripts

Ok so I am using a object orientated environment, I can make several scripts that may or may not connect with each other, all depending on if I want them to connect or not, and I want to get a function that is localized local myfunc = function() end from a different object that can handle code, from this point forward I will be calling these objects "Scripts" as they are what they are called in the game and are easily used for me to tell people what I am talking about even if they are not formally used as a name to suggest such a thing.
So lets say I have Script 1 with this code:
local myfunc = function() return true end
and I have Script 2 with a blank sheet, I want to make it so I can get myfunc without touching the debug library, making the original script a module script and returning the function, and this has to stay in 2 separate scripts. That is all for the requirements if you are wondering. I expect this can be done and I hope someone out there has the knowledge on how to do something like this clean and efficiently!
The whole point of a local variable is that it's local; other people can't touch it. The traditional means of having one script access data from another are modules or global variables. Both options which you have declared that you can't/won't do.
Your requirements reduce the set of possible solutions to zero.
Lua chunks can have return statements. To return a single function:
return function()
return true
end
To return a table with multiple functions:
return {
myFunc = function()
return true
end,
myOtherFunc = function()
return false
end,
}

Calling Functions 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).

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

Use of metatables in Lua

I'm trying to implement a object notation in Lua scripts.
Here is what I succeeded to do with the C API:
I created a new global table "Test" as a class and added a field "new" in it, pointing to a function written in C
i.e I can do this in lua code: "local obj = Test.new()" (it calls the function "new")
The "new" C function creates and returns a new table, and registers functions in it as fields (e.g "add", "count"...)
i.e I can do this: "obj:add("mike")" and "obj:count()" (obj is passed as first arguments with the ":" notation)
2 questions:
1) Everything works as expected, but the thing I'm wondering is: What is the advantage of using metatables in my case?
I see everywhere that metatables can help me to achieve what I tried to do, but I don't understand where they would be useful?
Adding fields to tables as methods isn't correct?
How could metatables help me (If added as my tables metatables)?
2) In fact I'm trying to reproduce the behaviour of C++ in Lua here.
For example, when I write this in C++: "Test *obj = new Test();"
I expect C++ and the constructor of Test to return me a pointer of an instance of Test.
This is exactly what I'm trying Lua to do for me.
The thing is that I use a table in this case, as the return of "new", but not a pointer so I can call methods on it later with Lua (using its fields), like a standard C++ object (with the operator ->).
To be able to retreive the actual pointer of my class in the C fonctions, I added a field "ptr" (light uservalue) to the table returned by "new". Without it, I would have been able to manipulate only the Lua table in my C function, nothing more (so no more method calls on the real pointer).
My second question is, Is it the right way to do it?
Do you have better idea on how to be able to manipulate my pointer everywhere without this "ptr" field?
Thank you,
Nicolas.
The main reason is that you get the __index metamethod.
Without it, every instance of a object has to have all the functions associated with it: which can make tables why large; and use a lot of memory.
local methods = {
foo = function() return "foo" end ;
bar = function() return "bar" end ;
bob = function() return "bob" end ;
hen = function() return "hen" end ;
}
So you have either
function new_no_mt ( )
local t = {}
for k , v in pairs ( methods ) do t [ k ] = v end
return t
end
vs
local mt = { __index = methods ; }
function new_mt ( )
return setmetatable ( { } , mt )
end
There are other benefits too;
defining operators;
easy type comparison via comparing metatables.
Changing method in metatable changes it for all objects, but changing it on one object only changes it for that object.
Otherwise, what you are trying to do sounds like the perfect situation for userdata.
userdata can only be indexed when you have an __index metatmethod (theres no table to put methods in)
What is the advantage of using metatables in my case?
Here's one.
Test.new = function() end
I just destroyed your ability to create new Test objects globally. If you had protected Test with a metatable, I would have had to really work to be able to do that.
Here's another:
local myTest = Test()
You can't do that without a metatable (overload the __call metamethod). And it looks much more natural for Lua syntax than calling Test.new.
And another:
local testAdd = Test() + Test()
Operator overloading. You can't do that without metatables.
Also:
This is exactly what I'm trying Lua to do for me.
Here's a tip: don't.
Different languages are different for a reason. You should do things in Lua the Lua way, not the C++ way. I can understand wanting to provide certain C++ mechanisms (like overloading and so forth), but you shouldn't use new just because that's what C++ uses.
Also, there are plenty of libraries that do this work for you. SWIG and Luabind are two big ones.

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