I'm just starting with Lua, and I have a problem with functions accessing local variables. The naive approach, just trying to access a variable, doesn't seem to work.
function fn1()
print(foo)
end
local foo = "Hello, world"
fn1() -- Prints nil
In this case, I could just pass foo to the function (as in fn(foo)), but that gets tricky with more complex cases.
function fn1()
fn2()
end
function fn2()
print(foo)
end
local foo = "Hello, world"
fn1(foo) -- Also prints nil
What is the correct way to access foo from inside the inner function? Passing foo to fn1 then to fn2 would work, but that gets difficult when there are several variables and functions involved. I would prefer not to make foo global. Are there any other ways to make this work?
You can do the following which puts the local in scope of both the functions.
local foo = "Hello, world"
function fn1()
fn2()
end
function fn2()
print(foo)
end
fn1()
Related
So i'm making my own OS for LIKO-12 and I need to run .lk12 files but i need to have a function to run a string as code and return a table that has all of the variables that code created
Example:
function foo()
return "Hello,"
end
function bar()
return " World!"
end
hello = foo()..bar()
should return a table with 2 functions:
A function called foo that returns "Hello,"
A function called bar that returns " World!"
and a variable called hello that has "Hello, World!"
You should be able to call a function from the code using
vars["foo"]() or vars.foo()
Can anyone help me?
When you create or use a global variable it's actually stored in a table called "the environment", or _ENV (which is not global, it's a local that you get automatically)
So your code:
function foo()
return "Hello,"
end
function bar()
return " World!"
end
hello = foo()..bar()
is really doing:
function _ENV.foo()
return "Hello,"
end
function _ENV.bar()
return " World!"
end
_ENV.hello = _ENV.foo().._ENV.bar()
so if we just set _ENV to a new table, and return it, then this is exactly the table you want. You can do this with load (which is how you run strings) by passing it as the 4th argument. This function will do that:
function loadAndReturnEnv(codeString)
local env = {}
load(codeString, nil, nil, env)() -- error checking skipped for demonstration
return env
end
However, note that all the usual global stuff like string.rep, table.sort, load, print don't exist in this new _ENV. If that's what you want, that's great. But I guess you probably do want them. In that case we can use the metatable __index feature, so that if the code looks for something in its _ENV and it's not there, it looks in our (the caller's) _ENV instead.
function loadAndReturnEnvWithGlobals(codeString)
-- note: env is the environment for the code we're about to run
-- (which will be called _ENV in that code), and _ENV is the environment
-- of the loadAndReturnEnvWithGlobals function (i.e. the "real" environment)
local env = {}
setmetatable(env, {__index=_ENV})
load(codeString, nil, nil, env)() -- error checking skipped for demonstration
setmetatable(env, nil) -- set the table back to normal before we return it
return env
end
But wait... the program can now call print when you run it, but if it defines a function, that function can't call print since we deleted the link back to the real environment after the code returned. So I think the best way to fix that is to leave the environment linked, and just copy the functions etc.
function loadAndReturnEnvWithGlobals2(codeString)
local env = {}
setmetatable(env, {__index=_ENV})
load(codeString, nil, nil, env)() -- error checking skipped for demonstration
local result = {}
for k,v in pairs(env) do result[k]=v end
return result
end
although this copies the values, so if you have any functions that change the variables, you won't see the changed variables.
Which version you use is up to you. They each have pros and cons.
Lets take a look at this pseudo code example:
-- Wraps a function with given parameters inside a callback
-- Usefull for sending class methods as callbacks.
-- E.g. callback(object.method, object)
local function callback(func, ...)
return function(...)
func(..., ...)
end
end
How would I go about this?
I know there is unpack, but it would get swallowed by the second vararg:
local function callback(func, ...)
local args = { ... }
return function(...)
func(table.unpack(args), ...)
end
end
callback(print, "First", "Second")("Third") --> prints First Third
The only option I found so far, is to concat those together and then unpack it:
local function callback(func, ...)
local args1 = { ... }
return function(...)
local args2 = { ... }
local args = { }
for _, value in ipairs(args1) do
table.insert(args, value)
end
for _, value in ipairs(args2) do
table.insert(args, value)
end
func(table.unpack(args))
end
end
Is this the only solution, or could I do better?
What I would like to have is either a function, that concats two arrays together (which should be faster than those two for loops) and then use table.unpack on it, or make those varargs concat.
From the Lua 5.4 Reference Manual: 3.4 Expressions
If an expression is used as the last (or the only) element of a list
of expressions, then no adjustment is made (unless the expression is
enclosed in parentheses). In all other contexts, Lua adjusts the
result list to one element, either discarding all values except the
first one or adding a single nil if there are no values.
So the only way is to manually combine both lists to a single one befor you use them.
There are several ways to do this.
for i,v in ipairs(list2) do
table.insert(list1, v)
end
for i,v in ipairs(list2) do
list1[#list1+i] = v
end
table.move(list2, 1, #list2, #list1 + 1, list1)
I'm not sure what kind of problem you're actually trying to solve here.
If you want to access your object from its methods use self.
-- Wraps a function with given parameters inside a callback
-- Usefull for sending class methods as callbacks.
-- E.g. callback(object.method, object)
Usually you would do something like this:
local callback = function(params) object:method(params) end
callback(params)
Instead of
callback(print, "First", "Second")("Third")
You could do this
local callback = function (...) print("First", "Second", ...) end
callback("Third")
Edit ( opinonated )
My main goal is to use member functions as callbacks. However, I'd
like to keep it general. The advantage of a callback function is to
omit the function and end keyword. It's shorter and looks closer to
what it would look like, if there would be no need for a self
argument. So this: object.event = function(...) return
self:method(...) end would become to this: object.event =
callback(self.method, self) what would be even nicer, is this (sadly
not possible in lua) object.event = self:method
So instead of
RegisterCallback(function() obj:method() end)
You say it is easier to do this, so you don't have to write function end?
local function callback(func, ...)
local args1 = { ... }
return function(...)
local args2 = { ... }
local args = { }
for _, value in ipairs(args1) do
table.insert(args, value)
end
for _, value in ipairs(args2) do
table.insert(args, value)
end
func(table.unpack(args))
end
end
RegisterCallback(callback(obj.method, obj)())
Your approach is not going to work if any of the arguments is nil to begin with. And there is not a single advantage. You're just typing other words while increasing the chance of running into errors.
You can control the param order to optimize your function.
local function callback(func, ...)
local args = {...}
return function(...)
func(..., table.unpack(args))
end
end
callback(print, "second", "third")("first") -- prints first second third
I have a function inside which I declared a global variable obs, inside a function and assigned some value.If I want to access this in some other lua file, it gives an error: "attempt to call obs a nil value, what do I need to do to able able to access it?
Here is the dummy code for it
//A.lua
function X()
obs = splitText(lk,MAXLEN)
end
//B.lua
function Y()
for i=1, #obs do //error at this line
end
end
There are a few ways to do this. With your current setup, you could do this:
a.lua
function x()
-- _G is the global table. this creates variable 'obs' attached to
-- the global table with the value 'some text value'
_G.obs = "some text value"
end
b.lua
require "a"
function y()
print(_G.obs); -- prints 'some text value' when invoked
end
x(); y();
Stuffing things in the global table is usually a terrible idea though, as any script anywhere else could potentially overwrite the value, nil out the variable, etc. a much better way imo would be to have your a.lua return its functionality in a table which you can capture in files which require it. this will allow you to define a getter function to return the 'obs' variable attached directly to your 'a.lua' functionality in its current state.
you probably want to do something like this for better portability (it is also much clearer which modules define which functionality this way):
a.lua
local obs_
function x()
obs_ = "some text value"
end
function get_obs()
return obs_
end
return { x = x, obs = get_obs }
b.lua
local a = require "a"
function y()
print(a.obs())
end
a.x()
y()
since you mentioned you can't use require, i'll assume you're working in some other framework that uses some other function to load libraries/files. in that case, you will probably have to just stuff everything in the global table. maybe something like this:
a.lua
-- this will attach functions a_x and a_get_obs() to the global table
local obs_
function _G.a_x()
obs_ = "some text value"
end
function _G.a_get_obs()
return obs_
end
b.lua
-- ignore this require, i'm assuming your framework has some other way loading
-- a.lua that i can't replicate
require "a"
function y()
print(_G.a_get_obs())
end
_G.a_x()
y()
Remember that some Lua programs inside other programs (Garry's Mod, World of Warcraft, Vera, Domoticz) uses _ENV instead of _G to limit their scope. So global variables has to be:
_ENV.variable = 1
instead of:
_G.variable = 1
The reason why this happens is because the developer wants to limit the standard Lua library to avoid that the user access methods like: os.exit().
To see if _ENV is used instead of _G, print it out and if it returns a table instead of nil, it's most likely used. You can also test with the following snippet:
print(getfenv(1) == _G)
print(getfenv(1) == _ENV)
Where the one to print true is the one you are using.
Why can't this Lua function using a self ":" be marked "local" without getting:
'(' expected near ':'
That is, in the code below things work. But why can't I make the "scene:createScene" function local (as I get the above-mentioned error when trying).
I note the listener functions need to be made local else I have struck cross-scene issues at times in storyboard. These can be marked local and work fine.
SceneBase = {}
function SceneBase:new()
local scene = Storyboard.newScene()
local function returnButtonTouch_Listener (event)
-- code here
end
function scene:createScene( event ) -- WHY CAN'T THIS BE LOCAL???
-- code here
end
return scene
end
return SceneBase
That is why can't the function line read:
local function scene:createScene( event )
function scene:createScene(event) ... end
Is syntax sugar for:
scene.createScene = function(self, event) ... end
Which is syntax sugar for:
scene["createScene"] = function(self, event) ... end
You want to do:
local scene["createScene"] = function(self, event) ... end
Which makes no sense.
Another way of putting it: local is a qualifier for a variable which makes it local rather than global. What variable would you be qualifying with local function scene:createScene( event )?
createScene is not a variable, it's a key in the table scene.
Actually, that's a bit misleading. When you say:
foo = 10
Without qualification, foo becomes global, which is to say it's stored in the global state like this:
_G.foo = 10;
Which of course means the same as this:
_G["foo"] = 10;
When you use the keyword local, it doesn't get stored in a table, it ends up stored in a VM register, which is both faster and has more tightly constrained scope.
When you write either of these:
function foo.bar() end
function foo:bar() end
You are explicitly storing the function value in a table (foo). Those statements are exactly equivalent to these, respectively:
foo["bar"] = function() end
foo["bar"] = function(self) end
I note the listener functions need to be made local
What do you mean by that? In Lua, a function is a function is a function. It's just another value, like a string or number. Whether it's stored in a global, table, local, or not stored at all is irrelevant.
local foo = print
_G["zap"] = foo
doh = zap
t = { zip = doh }
t.zip("Hello, World") -- Hello, World
assert(print == foo
and zap == foo
and zap == doh
and t.zip == doh)
Here we pass the print function around. It's all the same function, and as long as we have a reference to it we can call it.
I don't know Corona, but I'm guessing that event handlers are not specified by naming convention of locals. You need to register it as an event handler. For instance, according to this video a Button object has an onEvent field which is set to the handler for that button.
I am taking my first steps programming in Lua and get this error when I run my script:
attempt to index upvalue 'base' (a function value)
It's probably due to something very basic that I haven't grasped yet, but I can't find any good information about it when googling. Could someone explain to me what it means?
In this case it looks base is a function, but you're trying to index it like a table (eg. base[5] or base.somefield).
The 'upvalue' part is just telling you what kind of variable base is, in this case an upvalue (aka external local variable).
One "local" too many?
As Mike F explained, an "upvalue" is an external local variable. This error often occurs when a variable has been declared local in a forward declaration and then declared local again when it is initialized. This leaves the forward declared variable with a value of nil. This code snippet demonstrates what not to do:
local foo -- a forward declaration
local function useFoo()
print( foo.bar ) -- foo is an upvalue and this will produce the error in question
-- not only is foo.bar == nil at this point, but so is foo
end
local function f()
-- one LOCAL too many coming up...
local foo = {} -- this is a **new** foo with function scope
foo.bar = "Hi!"
-- the local foo has been initialized to a table
-- the upvalue (external local variable) foo declared above is not
-- initialized
useFoo()
end
f()
In this case, removing the local in front of foo when it is initialized in f() fixes the example, i.e.
foo = {}
foo.bar = "Hi!"
Now the call to useFoo() will produce the desired output
Hi!