Lua custom operators - lua

I am trying to create an operator '!' that returns the print function.
I am getting the following error:
line 15: attempt to call a number value
stack traceback:
t.lua:15: in main chunk
[C]: ?
My code is below:
local opTable = {}
debug.setmetatable(0,{
_call = function(a,op)
return opTable[op](a)
end
})
local function addOp(operator,f)
opTable[operator] = f
end
addOp('!',print)
print((5)'!')
It seems this should work, because techniqe #3 on http://lua-users.org/wiki/CustomOperators uses almost exactly the same method.

Related

Error with push.lua from CS50 game course

I have a problem with the folder "pong-1" that contains "main.lua" and "push.lua". When I select them into "LÖVE", it says:
>Error
push.lua:71: bad argument #1 to 'insert' (table expected, got number)
[C]: in function 'insert'
push.lua:71: in function 'setupCanvas'
main.lua:12: in function 'load'
[C]: in function 'xpcall'
[C]: in function 'xpcall'
I tried with the outdated version of push.lua (which offers the source code of the course) as well as the newest version I could find, but neither of them worked. Both display the same error message. What could be the problem?
function push:setupCanvas(canvases)
table.insert(canvases, { name = "_render", private = true }) --final render
self._canvas = true
self.canvases = {}
for i = 1, #canvases do
push:addCanvas(canvases[i])
end
return self
end
This functions expects canvases to be a table value.
You provide a number value VIRTUAL_WIDTH in your function call
push:setupCanvas(VIRTUAL_WIDTH, VIRTUAL_HEIGHT, WINDOW_WIDTH,
WINDOW_HEIGHT,{ fullscreen = false, resizable = false, vsync = true })
instead.
Looks like you're confusing setupCanvas with setupScreen

Store function to indexed arrays and call him with undefault param

I'm trying to create and indexed array of functions to call him with changed params, like this:
local function wubba(lubba)
return lubba
end
local dub = {
["wubba"] = {func = wubba(lubba)}
}
print(dub["wubba"].func("hi"))
But in all my tries i got errors, i can't figure out how to do it. Anyone can help me?
lua: wubba.lua:9: attempt to call field 'func' (a nil value)
stack traceback:
wubba.lua:9: in main chunk
[C]: in ?
Solved, just not to store with params:
local dub = {
["wubba"] = {func = wubba}
}

Getting access to parameter inside a string being executed with 'load'

I would like to know if there's a way for the 'load' function to get a variable value from a local variable instead of a global variable ?
Say that I've got a string like this 'trade.version == 2' that I want to execute with the 'load' function inside a function taking the trade as parameter.
function doTest( trade, test )
-- inside the string 'test', I would like that any reference to 'trade'
-- refer to the function parameter instead of a global variable
if ( assert(load("return "..test))() ) then
-- do something
end
end
a_userdata = { version = 2 }
-- Calling the function above
doTest( a_userdata , "trade.version == 2" )
[string "return trade.version == 2"]:1: attempt to index global 'trade' (a nil value)
stack traceback:
[string "return trade.version == 2"]:1: in main chunk
stdin:2: in function 'doTest'
stdin:1: in main chunk
[C]: in ?
As a workaround, I have defined a global variable and it's working pretty fine.
But I would like to avoid this global variable.
Thank you very much
function doTest( trade, test )
-- inside the string 'test', I would like that any reference to 'trade'
-- refer to the function parameter instead of a global variable
if assert(load("local trade = ...; return "..test))(trade) then
-- do something
print('Yes, version equals to 2')
end
end
a_userdata = { version = 2 }
-- Calling the function above
doTest( a_userdata , "trade.version == 2" )

lua's loadstring() not working with tables

I have some text and I'm trying to load it via load string. The following works:
local m = loadstring("data = 5")()
But when the data is a table it doesn't work and gives the error "attempt to call a nil"
local m = loadstring("data = { 1 = 10}")()
The table declaration in lua require integer keys to be put inside square brackets:
data = {
[1] = value,
}
The enclosing of keys in square brackets is always allowed, valid and possible. It can be skipped iff your key follows the pattern: [A-Za-z_][A-Za-z0-9_]* (which is the same as a valid variable name in lua)
If you had added an assert you would have got a more helpful message:
local m = assert (loadstring("data = { 1 = 10}"))()
Result:
stdin:1: [string "data = { 1 = 10}"]:1: '}' expected near '='
stack traceback:
[C]: in function 'assert'
stdin:1: in main chunk
[C]: ?
And to actually answer the question, unless the table key happens to follow Lua variable naming rules, you have to put it inside square brackets, eg.
local m = assert (loadstring("data = { [1] = 10}"))()
m is still nil when I do this
What does that matter? The loadstring is done.
Just do this:
assert (loadstring("data = { 1 = 10}"))()
print (data [1])
You don't need the variable m. The loadstring puts a table into data - that is the important thing.

_ENV & classes in Lua are not being compatible

_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.

Resources