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
Related
I have the following code:
dofile(arg[1])
function1 = arg[2]
argument = arg[3]
returned = _G[function1](argument)
print(returned)
It is designed to take three command-line arguments and run a function from a file.
So, i run the command lua libs.lua "printStuff.lua" "printStuff" "\"Hello, World\"", and i always end up with this:
"Hello, World"
nil
I don't understand why i always get "nil".
Here are the contents of printstuff.lua:
function printStuff(stuff)
print(stuff)
end
That is to be expected. What's going on here:
You're executing the file specified by the first argument, printstuff.lua, which will leave a function printStuff in the global table _G.
You're indexing the global table with the second argument, printStuff, obtaining that function
You're calling the function you just obtained with the third command line argument, "Hello World!", as parameter, which prints it, and storing the result of that in the global variable returned. The function printStuff doesn't return anything (there's no return in there, and even if there was, print doesn't return anything either), so you're assigning nil to returned.
You're printing returned, which is nil
Side note: I'd use the vararg ... instead of the arg table for improved readability:
local file, func, param = ...
dofile(file); print(func(param))
Why not simply...
-- xlua.lua
-- Example: lua xlua.lua os date "%H:%M:%S"
-- Or: lua xlua.lua _G print "Hello World"
-- Or: lua xlua.lua dofile /path/to/someusefull.lua "Arg for someusefull.lua"
local result = _G[arg[1]][arg[2]](arg[3])
-- 5. Only put out whats not nil
if (result ~= nil) then
print(result)
end
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.
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
}
I am sure I am missing something ridiculously simple, but I stared at this long enough to ask for your help. I am trying to write the simplest of all loggers, and when I'm trying to run it, it's not seeing the global variable (that I (think) I declare!). I am an "advanced" beginner in lua, so silly mistakes are not as common, but still do happen in my case. Please, tell me what I'm missing here!
Here's the logger code, and I'm testing it within the script....
local type, pairs, table, tostring, io, os, print = type, pairs, table, tostring, io, os, print
local file
LEVELS = {}
LEVELS ["ERROR"] = 0
LEVELS ["WARN"] = 1
LEVELS ["INFO"] = 2
LEVELS ["DEBUG"] = 3
print (LEVELS.WARN)
local level
function init (outputFile, debugLevel)
level = debugLevel
file = io.open(outputFile, "a")
local ret
if (file == nil) then ret = false else ret = true end
return ret
end
function warn (message)
if level ~= nil and level >= LEVELS.WARN and file ~= nil then
log(message)
end
end
function log (message)
local timestamp = os.date()
file:write(timestamp..' - '..message..'\n')
file:flush()
end
function deInit ()
file:close()
end
init ("testInsideLogger.lua", 3)
warn("HI")
deInit()
What I get in the output:
Print right after the declaration of LEVELS works, prints out 1.
But when I call the warn("HI") method, I get
attempt to index global 'LEVELS' (a nil value).
WHY???
Thank you so much for your help!
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!