Using a global variable in different Lua script in different folder - lua

I have a a global variable defined in a file named folder1/config.lua as : max_channel = 40 .
Now I would like to use this value in an anthors script in a different folder say: folder2/script2.lua here is what I've tried:
local channel = require "folder1/config"
numberOfchannel = channel.max_channels
When I try to use numberOfchannel the compiler consider it as a string not a integer of value 40. Why is this?
UPDATE: Here is how I try to use the numberOfchannel:
if num < numberOfchannel then
...........
attempt to compare number with nil
knowing that num is a number and that the if statement works fine when I put for example 40
and here is the begging of the file folder1.config.lua:
module(..., package.seeall)
max_channels = 40
UPADTE
After greatwolf suggestion I tried to show the content the channel the local variable but I've got an error messagre saying :
stdin:1: bad argument #1 to 'pairs' (table expected, got nil)
stack traceback:
[C]: in function 'pairs'
stdin:1: in main chunk
[C]: ?

module is deprecated.
In config.lua, just do:
return {
max_channels = 40
}

Related

Get complete stacktrace of a coroutine, including where a coroutine is resumed

A simple example:
coroutine.resume(coroutine.create(function()
print(debug.traceback())
end))
print(debug.traceback())
the output:
stack traceback:
./v.lua:2: in function <./v.lua:1>
stack traceback:
./v.lua:4: in main chunk
[C]: in ?
It shows that traceback inside a coroutine doesn't know about how it is resumed, so that xxx: in main chunk doesn't show.
How can I get the complete stacktrace inside a coroutine?
Well, I found a workaround here.
Since one Lua VM has only one execution point at one time (and that's why a full call stack is there), we can record resumption information manually.
In lua, manually build a resume-stack trace.
local xresume = coroutine.resume
local xtrace = debug.traceback
-- magic here! Take care of main thread.
local mainthr = coroutine.running() -- captureing is a must.
debug.traceback = function(athr)
if athr then return xtrace(athr) end -- no interest in specified thread.
return xtrace(mainthr)
end
coroutine.resume = function(thr, ...)
-- another magic.
local uptrace = debug.traceback
debug.traceback = function(athr)
if athr then return xtrace(athr) end -- no interest in specified thread.
return xtrace(thr) -- trace the stack of thr.
.. '\n' .. uptrace() -- trace from thr's resume point.
end
local result = { xresume(thr, ...) }
debug.traceback = uptrace
return table.unpack(result)
end
Other tips:
Using global table to store threads also works. But you still need to capture main thread so that it can be traced everywhere.
Writing codes in C function can prevent traceback into hooked coroutine.resume and debug.traceback itself, give you a clearer output.
You won't get much performance hit when debug.traceback is not called.

Getting "attempt to index a nil value error" when attempting to create objects in Lua

I'm putting some code into a module so I can draw and maintain multiple copies. I'm getting this common error but I can't see why. I understand what it's saying to a basic level, but as I'm able to see a print out from the table being created, I don't understand why calling a function that module contains would throw this error.
I've read through all the answers on SO, but I'm still at a loss. I've tried printing out at various stages to see where the issue is, everything works as if I had created an instance of the module, but the error persists.
Code below is cleaned of extraneous stuff.
local orbitalCircle = include('lib/orbital_circle')
function init()
c1 = orbitalCircle.new(20, 42, 18, 1.7, 16, 62, 15, c1Sequence)
<-- at this point print code from the module's init function works
c1:doFunc(param) <-- this will call the error
The module:
local Orbital_Circle = {}
-- set up variables
local some Vars Are here
function Orbital_Circle.new(x, y, diameter, scale_factor, number_of_notes, beats_per_second, frames_per_second, sequence_data)
print("Orbital_Circle running")
end
function Orbital_Circle:doFunc(param)
self.var = param <-- I update a local var here
print("self.var") <-- I then print the updated number for sanity checking
end
return Orbital_Circle
I expect the var in my instance of this module to update and the functions code to run, but... no joy. I get the error.
Cheers.
I'm putting some code into a module so I can draw and maintain multiple copies.
I think there's a bit of a misunderstanding about how Lua modules work here. It's an easy mistake to make.
When you require a module in Lua, each subsequent require of the same file refers to the same code. So (eg) these two variables contain exactly the same code:
local orbitalCircle1 = require('lib/orbital_circle')
local orbitalCircle2 = require('lib/orbital_circle')
Which means that you can't use Lua modules by themselves to create OOP type objects as you are trying to do. Your new function must return something that can be used like an instance of a class, a unique table for each call:
local Orbital_Circle = {}
local shared_variable = 1
function Orbital_Circle.new(x, y)
-- create unique table
local obj = {}
-- access these from table/object methods with self.xxx
obj.x = x or 0
obj.y = y or 0
obj.var = "initial value"
-- now define functions with an explicit 'self' parameter...
function obj.doFunc(self, param)
self.var = self.var .. " " .. param
shared_variable = shared_variable + 1
end
-- ... or with the syntactic 'self' sugar, ':'
function obj:printVars()
print("self.var = " .. self.var)
print("shared_variable = " .. shared_variable)
print("self.x = " .. self.x)
end
return obj
end
return Orbital_Circle
You can also define the methods as local functions outside the new function that have self parameter and have a list of entries such as:
obj.anotherMethod = functionDeclaredAtTopOfFile
… to keep things tidier, if you like.
Your code is completely messed up.
<-- will cause an error for unexpected symbol.
c1 = orbitalCircle.new(20, 42, 18, 1.7, 16, 62, 15, c1Sequence)
will give you an error for indexing a global nil value c1 because orbitalCircle.new has no return value.
your init function is incomplete and you don't call it so the provided code does not do anything even if you fix the above errors.
The reported error is not caused by any line of code you provided here.
Code below is cleaned of extraneous stuff.
I'm afraid you removed too much.
The error message tells you that you're indexing local n, a nil value from within a local function that has been defined in n's scope.
This code for example:
local n
function test()
local b = n.a
end
test()
would result in the error message:
input:3: attempt to index a nil value (upvalue 'n')
n is an upvalue for test because it is a local variable defined outside the functions body, but not a global variable.

How does debug.traceback get its information?

With the below code from the Lua demo page, I was trying to get the name of the function being pcalled.
function test()
local info = debug.getinfo(1);
for k, v in pairs(info) do
print(k, v);
end;
end;
pcall(function()
test();
end);
This was a success, as I received the following output, containing the name:
source =input
func function: 0x25a1830
nparams 0
short_src input
isvararg false
name test
namewhat global
istailcall false
linedefined 1
lastlinedefined 7
nups 1
currentline 2
what Lua
If I change the code to the following, I no longer get that information:
function test()
local info = debug.getinfo(1);
for k, v in pairs(info) do
print(k, v);
end;
end;
pcall(test);
The output is as follows:
func function: 0x21ee790
linedefined 1
nups 1
short_src input
namewhat
lastlinedefined 7
isvararg false
istailcall false
what Lua
source =input
currentline 2
nparams 0
If, however, I change the code to the following, I can obtain the name of the function passed to pcall:
function test()
local traceback = debug.traceback();
print(traceback);
end;
pcall(test);
With the output being as follows:
stack traceback:
input:2: in function 'test'
[C]: in function 'pcall'
input:7: in main chunk
[C]: in function 'pcall'
demo.lua:49: in main chunk
[C]: in ?
How does debug.traceback get this extra information, and using solely Lua is there a way to get it without extracting it from debug.traceback's return value?
debug.getinfo and debug.traceback get their info from various sources, some of them hacky. For instance, the function name is generally extracted from the source code of the calling function: whatever name the code used to look up the thing it called, that's what gets used as the name. (That's why your second code snippet didn't give you the name: pcall doesn't have Lua bytecode backing it up, so it can't tell you "test" unless there's a function in the middle to call it "test".) Lua functions do not have inherent names, any more than Lua integers do; a function is just another kind of value, which can be automatically assigned to a variable via some syntactic sugar.
Functions are values. Values don't have names.
Functions are not "declared" as in some other languages. A function value is created when a function definition is evaluated.
Debugging output is just trying to be helpful in simple cases by giving the name of a variable associated with calling the function value.

Lua flexible function argument unpacking in local function

I am working on command handler that needs to work in two environments. Below is a a small part of the function I am working on, which I think captures the problem. At least, I get the error message I need to adress.
In the live environment, a Fibaro Home center 2, command sets given in the table should be executed one by one using fibaro:call, which takes 2-3 arguments, depending the call.
During development I instead use the print function to just print the commands that should have been issued.
function movementHandler(movementSendorId,onTable)
local offTable = offTable or {};
local onTable = onTable or {};
if (fibaro or {}).call then
function callFunc(...) ;
return fibaro:call(...);
end;
else
function callFunc(...)
print(unpack(arg));
end;
end;
if onTable ~= {} then
for i,command in pairs(onTable) do
callFunc(unpack(command));
end;
end;
end;
However, when I try this in the Lua command shell
> c= {}
> c[1] = {1,"turnOn"}
> c[2] = {1,"setValue",10}
> movementHandler(10,c,c)
, I get this output:
stdin:10: bad argument #1 to 'unpack' (table expected, got nil)
stack traceback:
[C]: in function 'unpack'
stdin:10: in function 'callFunc'
stdin:15: in function 'movementHandler'
stdin:1: in main chunk
[C]: in ?
What I am not understanding about how unpack works?
Automatic creation of the arg table for vararg functions was deprecated in Lua 5.1 and removed in Lua 5.2.
Use simply
function callFunc(...)
print(...)
end
If you need a table, use
function callFunc(...)
local arg={...}
print(unpack(arg))
end

attempt to call method 'random' (a nil value) in Lua

Below is my code
require 'dpnn'
require 'cunn'
local deviceNumber = tonumber(os.getenv("CUDA_CARD_NR"))
cutorch.setDevice(deviceNumber)
local module = nn.Sequential():cuda()
module:add(nn.Linear(2,1):cuda())
module:add(nn.Sigmoid():cuda())
criterion = nn.BCECriterion():cuda() -- Binary Cross Entorpy Criteria
local targets = torch.CudaTensor(10):random(0,1)
local inputs = torch.CudaTensor(10,2):uniform(-1,1)
function trainEpoch(module,criterion,inputs,targets)
for i=1,inputs:size(1) do
local idx = math.random(1,inputs:size(1))
local input, target = inputs[idx], targets:narrow(1,idx,1)
-- forward
local output= module:forward(input)
local loss= criterion:forward(output,target)
-- backward
local gradOutput = criterion:backward(output,target)
module:zeroGradParameters()
local gradInput = module:backward(input,gradOutput)
--update
module:updateGradParameters(0.9) -- momentum
module:updateParameters(0.1) -- W = W -0.1*dL/dW
end
end
for i=1,100 do
trainEpoch(module,criterion,inputs,targets)
end
I am running above using the following command
CUDA_CARD_NR=1 luajit feedforwad.lua
It gives the following error
luajit: feedforwad.lua:13: attempt to call method 'random' (a nil value)
stack traceback:
feedforwad.lua:13: in main chunk
[C]: at 0x004064f0
I know that there is some error in the line
local targets = torch.CudaTensor(10):random(0,1)
But I am not able to figure out.
luajit: feedforwad.lua:13: attempt to call method 'random' (a nil
value)
Is not "some error" and you should not have problems to figure out what is wrong because the error message tells you exactly what is wrong.
You tried to call the a method named random which happens to be a nil value.
This means that there is no function with that name and therefor you can't call it.
According to the reference documentation (which you should have checked befor coming here) the function is actually named rand

Resources