I am using Gideros and getting this error:
main.lua:47: attempt to index a nil value
stack traceback:
main.lua:47: in function 'func'
[string "compatibility.lua"]:36: in function <[string "compatibility.lua"]:35>
I have this piece of code and as soon as the text is displayed, it gives me the above mentioned error:How can I fix this?
function onEnter()
function youLoose()
local font2 = TTFont.new("billo.ttf", 20, "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
LooserText = TextField.new(font2, "You Loose , Try AGAIN?")
LooserText:setPosition(100, 100)
stage:addChild(LooserText)
Timer = Timer.delayedCall(1000, removing)
end --line 36
end
function removing()
LooserText:getParent():removeChild(LooserText) --line 47
end
The index nil error means that on that line you are probably getting nil as a return value from LooserText:getParent().
Why you would be getting nil for that I can't tell you other than presumably because it doesn't have one.
The documentation indicates that there is no error condition for Stage.addChild except that the object added must be a Sprite. TextField inherits Sprite so there is no apparent reason for you to get this error. However, you should not re-assign the return value of delayedCall to a global variable of same name as the Timer class, this could affect other parts of the application. Since you don't use the returned Timer instance, I have removed the assignment. Also, if the stage:addChild succeeded then the removing can use stage. One thing that is strange is that your onEnter just defines youLose() but does not call it or return it, is this part of code you ommitted? In any case, you need to add some sanity checks to verify that what you think is happening is really happening w/r/t child add/remove:
function onEnter()
function youLoose()
local font2 = TTFont.new("billo.ttf", 20, "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
LoserText = TextField.new(font2, "You Lose , Try AGAIN?")
LoserText:setPosition(100, 100)
print('Stage num children:' .. stage:getNumChildren())
stage:addChild(LoserText)
print('Stage num children:' .. stage:getNumChildren())
print('LoserText is stage child #' .. stage:getChildIndex(LoserText))
Timer.delayedCall(1000, removing)
end
end
function removing()
print('Stage num children:' .. stage:getNumChildren())
print('LoserText is stage child #' .. stage:getChildIndex(LoserText))
stage:removeChild(LoserText)
print('Stage num children:' .. stage:getNumChildren())
end
Related
hope you having great day , i'm test some stuff with lua, and i got some error
i have this codes in Object.lua
local Object = {name = "Object"}
Object.__index = Object
function Object.new()
local t = setmetatable({}, Object)
return t
end
function Object:keys(table)
local keyset={}
local n=0
for k,v in pairs(table) do
n=n+1
keyset[n]=k
end
return keyset
end
return Object
and i call Object.keys in "Other" script like this
local Object = require("lua.app.common.utils.Object")
local t = {
[1] = a,
[2] = b,
[3]= c
}
Object.keys(t)
and this cause error with
Exception has occurred: bad argument #1 to 'for iterator' (table expected, got nil),
because the parameter 'table' is passed as nil ( i don't know why thuogh debug mode just says its a nil)
on the other hand, if i fix object.keys(table) to object:keys(table), everything works fine, why this error happening?
Declaring the method keys with a colon adds an implicit self parameter as the first argument which requires you to call the method in the same way, using the colon.
Calling the method with the period notation expects you to supply the self parameter but because you only pass in t this is interpreted as self and then nil is added for your table parameter.
Declaring the method with a colon you actually have this
function Object:keys(self, table)
but calling it with the period means you have done this
Object.keys(t, nil)
hence the "table expected, got nil" error
I'm learning game development with LÖVE2D and Lua and lately I've been using a state machine class. I haven't coded the class myself, but I've went through the code and I think I pretty much got it, besides this one problem.
The thing is, I'm trying to prompt the class for its current state, just so I can use it inside an if, but no matter what, I cannot get it right.
Here's the relevant code of the class:
StateMachine = Class{}
function StateMachine:init(states)
self.empty = {
render = function() end,
update = function() end,
enter = function() end,
exit = function() end
}
self.states = states or {} -- [name] -> [function that returns states]
self.current = self.empty
end
function StateMachine:change(stateName, enterParams)
assert(self.states[stateName]) -- state must exist!
self.current:exit()
self.current = self.states[stateName]()
self.current:enter(enterParams)
end
What I'm basically trying to do is:
function StateMachine:is(stateName)
if self.current == self.states[stateName] then
-- this never executes
return true
end
return false
end
I've tried changing self.states[stateName] to other things to test it out and also tried printing stuff to the console to see why the comparison is never true. It seems self.current returns a pointer to a table and thus never matches whatever is on the other side of the comparison operator.
Thanks for your help!
self.current is set to the return value of self.states[stateName] in StateMachine:change
function StateMachine:change(stateName, enterParams)
...
self.current = self.states[stateName]() -- note the () indicating the call
This means, unless the return value is self, self.current will not be equal to the function or object self.states[stateName] that it is compared to in StateMachine:is
function StateMachine:is(stateName)
if self.current == self.states[stateName] then -- here we are comparing the function to the return value
I would suggest expanding your state object to have a :getName function that would return the stateName or to store the name in your StateMachine under a key such as currentStateName.
I had the exact same question & I'd like to add--perhaps some of the comments explain this in language I just didn't understand :D--but in the getCurrentState function I created I had to do this:
function StateMachine:getCurrentState()
variable = self.currentStateName
return variable
where ofc variable is just some placeholder. but I had to grab the reference that self.currentStateName was pointing to, otherwise the comparison always failed.
I'm trying to secure the doors of my CNC with switchs that send a Signal to my Laptop (I got Mach 4 on it). I created this Code that should make the Spindle stay still if the doors aren't locked, but I always get an error that says :
[string""]1576 attempt to call global 'SicherheitsKreis' (a Nil value) stack traceback:
I've tried to move the Code around and read topics on this, but Nothing works.
Does someone have a solution ?
Here's all my Code :
function SicherheitsKreis(Schliesserstate, Oeffnerstate)
if (Schliesserstate ==0 and Oeffnerstate ==1 ) then
mc.mcSpindleSetDirection(inst,0)
elseif (Schliesserstate == 1 and Oeffnerstate == 0 ) then
local sigh = mc.mcSignalGetHandle(inst, mc.OSIG_SPINDLEON);
local sigState = mc.mcSignalGet State(sigh);
if (sigState == 1) then
mc.mcSpindleSetDirection(inst,0)
else
mc.mcSpindleSetDirection(inst,1);
end
else
mc.mcSpindleSetDirection(inst,0)
end
end
if (mc.mcInEditor() == 1) then
SicherheitsKreis()
end
The Code that I'm using to call SicherheitsKreis is :
local inst = mc.mcGetInstance()
local hsigSchliesser = mc.mcSignalGetHandle(inst, mc.ISIG_INPUT8);
local hsigOeffner = mc.mcSignalGetHandle (inst, mc.ISIG_INPUT9);
local Schliesserstate = mc.mcSignalGetState(hsigSchliesser);
local Oeffnerstate = mc.mcSignalGetState(hsigSchliesser);
SicherheitsKreis(Schliesserstate, Oeffnerstate)
This Script is typed in Mach 4 and the function is saved as a m function (nach4 has free m function that the user can customize) in the Memory of Mach 4 (for my Computer it is m146)
Your code:
function SicherheitsKreis(Schliesserstate, Oeffnerstate)
...
end
First possibility is that code is in some other function or other element, so it is not global. Second possibility is that you run SicherheitsKreis(Schliesserstate, Oeffnerstate) before loading this part of code. Third (very uncommon) is that you override it by SicherheitsKreis = nil or equivalent. There is no other possibilities.
This is my first time using metatables, I did a simple script to test in Lua demo but it always give me "attempt to call method 'rename' (a nil value)", why?
peds = {}
function peds.new ( name )
local tb = { name = name }
setmetatable ( tb, { __index = peds } )
return tb
end
function peds.rename ( name )
self.name = name
return self.name == name
end
local ped = peds.new ( "max" )
ped:rename ( "randomname" )
There's two (possible) problems in your code, depending on how you are setting things up.
If you are just typing the above into a REPL, then when you declare local ped = ... it immediately goes out of scope and becomes inaccessible. So the expression ped:rename is invalid, although it should report "ped is nil" not "rename is nil".
If you are saving the above to a script and loading it using load_file or something, you will still get a problem, because this function signature isn't right:
function peds.rename ( name )
should be:
function peds.rename ( self, name )
Similar to how it works in C++, in lua, when you make an object method, you have to take the hidden self parameter first, and when you call ped:rename( "random name" ) that's just syntactic sugar for ped.rename(ped, "random_name"). If the self parameter doesn't exist then it's not going to work, or may even say "function not found / rename is nil" because the signatures don't match up.
_ENV currently hates using classes. I'm attempting to create a Latin kind of Lua, and some things can't precisely be made with _ENV but it's a lot more efficient. setfenv was being uncooperative as well.
The subsequent code keeps returning the old attempt to call a nil value error. It specifies line 20, in which loadstring() is being checked, and line 23, where in the main chunk it is calling the __latin() function.
function __latin(code)
__predecessor = [===[
function typographia(value)
print(value);
end
chorda = {};
chorda.__index = chorda;
function chorda.sub(chorda, cChorda, fChorda)
return string.sub(chorda, cChorda, fChorda);
end
function chorda:sub(chorda, cChorda, fChorda)
return string.sub(chorda, cChorda, fChorda);
end
--[[ define values --]]
_ENV = {salve="Salve, munde!",typographia=typographia,print=print,chorda=chorda,chorda.sub=chorda.sub}; ]===];
__finalizer = __predecessor .. " " .. code;
local status, err = pcall(loadstring(__finalizer));
print(err);
if (err == nil) then loadstring(__finalizer)(); end
end
__latin('typographia(salve); chorda.sub(salve, 1, 3);');
You're getting "attempt to call a nil value" because loadstring returns nil (so you're calling pcall with nil). loadstring returns nil because the code you're compiling (__predecessor) contains invalid Lua:
_ENV = {
chorda.sub = chorda.sub -- can't do this
}
FYI: The loadstring/pcall stuff is irrelevant to your problem. Had you stripped it out before posting, you would have found this error yourself.