lua table global/local var getting confused - lua

I have a lua table which I used to share values between files. But I am getting confused in the following case
utility.lua file
M = {}
M.host_url = '192.168.0.1'
function M.myFunc()
print(M.host_url )
end
return M
in my main.lua
utility = require('utility')
utility.myFunc() -- this gives me 'a nil value' error
I get an error (nil value) for the host_url?

In M.myFunc doing only print action that function nothing will be return.in your utility file returning whole array see he below code that will clear your doudt.
In main.lua
utility = require('util')
value = utility.host_url
print(value)

Related

lua - differece of : and . when define function?

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

Simple LZW Compression doesnt work

I wrote simple class to compress data. Here it is:
LZWCompressor = {}
function LZWCompressor.new()
local self = {}
self.mDictionary = {}
self.mDictionaryLen = 0
-- ...
self.Encode = function(sInput)
self:InitDictionary(true)
local s = ""
local ch = ""
local len = string.len(sInput)
local result = {}
local dic = self.mDictionary
local temp = 0
for i = 1, len do
ch = string.sub(sInput, i, i)
temp = s..ch
if dic[temp] then
s = temp
else
result[#result + 1] = dic[s]
self.mDictionaryLen = self.mDictionaryLen + 1
dic[temp] = self.mDictionaryLen
s = ch
end
end
result[#result + 1] = dic[s]
return result
end
-- ...
return self
end
And i run it by:
local compressor = LZWCompression.new()
local encodedData = compressor:Encode("I like LZW, but it doesnt want to compress this text.")
print("Input length:",string.len(originalString))
print("Output length:",#encodedData)
local decodedString = compressor:Decode(encodedData)
print(decodedString)
print(originalString == decodedString)
But when i finally run it by lua, it shows that interpreter expected string, not Table. That was strange thing, because I pass argument of type string. To test Lua's logs, i wrote at beggining of function:
print(typeof(sInput))
I got output "Table" and lua's error. So how to fix it? Why lua displays that string (That i have passed) is a table? I use Lua 5.3.
Issue is in definition of method Encode(), and most likely Decode() has same problem.
You create Encode() method using dot syntax: self.Encode = function(sInput),
but then you're calling it with colon syntax: compressor:Encode(data)
When you call Encode() with colon syntax, its first implicit argument will be compressor itself (table from your error), not the data.
To fix it, declare Encode() method with colon syntax: function self:Encode(sInput), or add 'self' as first argument explicitly self.Encode = function(self, sInput)
The code you provided should not run at all.
You define function LZWCompressor.new() but call CLZWCompression.new()
Inside Encode you call self:InitDictionary(true) which has not been defined.
Maybe you did not paste all relevant code here.
The reason for the error you get though is that you call compressor:Encode(sInput) which is equivalent to compressor.Encode(self, sInput). (syntactic sugar) As function parameters are not passed by name but by their position sInput inside Encode is now compressor, not your string.
Your first argument (which happens to be self, a table) is then passed to string.len which expects a string.
So you acutally call string.len(compressor) which of course results in an error.
Please make sure you know how to call and define functions and how to use self properly!

why is my global table being considered nil?

background:
I am trying to teach myself Lua and I am having difficulty understanding why a table is being considered nil when it has data inside it. Can anyone break it down for me why I am getting this error message from the code snippet below? It is one of my first programs and i really need to get these few concepts down before moving on to my real project. Thanks!
error message:
C:\Users\<user>\Desktop>lua luaCrap.lua
lua: luaCrap.lua:7: attempt to call global 'entry' (a nil value)
stack traceback:
luaCrap.lua:7: in main chunk
[C]: ?
code:
--this creates the function to print
function fwrite (fmt, ...)
return io.write(string.format(fmt, unpack(arg)))
end
--this is my table of strings to print
entry{
title = "test",
org = "org",
url = "http://www.google.com/",
contact = "someone",
description = [[
test1
test2
test3]]
}
--this is to print the tables first value
fwrite(entry[1])
--failed loop attempt to print table
-- for i = 1, #entry, 1 do
-- local entryPrint = entry[i] or 'Fail'
-- fwrite(entryPrint)
-- end
you are missing the assignment to entry.
you need to change the entry code to this:
entry =
{
title = "test",
org = "org",
url = "http://www.google.com/",
contact = "someone",
description = [[
test1
test2
test3]]
}
to clarify the error message, parens are assumed in certain contexts, like when you have a table directly following a label. the interpreter thinks you're trying to pass a table to a function called entry, which it can't find. it assumes you really meant this:
entry({title = "test", ...})

Lua Metatables - calling functions with colon syntax

I have the following problem, somebody can help me?
comp = {}
comp.__index = function(obj,val)
if val == "insert" then
return rawget(obj,"gr")["insert"]
end
return rawget(obj, val)
end
comp.new = function()
local ret = {}
setmetatable(ret, comp)
ret.gr = display.newGroup()
return ret
end
local pru = comp.new()
pru.gr:insert(display.newImage("wakatuBlue.png"))
This line works, but I don't want to access the insert method using the gr property, I want to call the insert method directly and the metatable __index function does the work
pru:insert(display.newImage("wakatuBlue.png"))
This line doesn't work and I get this error: "bad argument #-2 to 'insert' (Proxy expected, got nil)", but this is the way that I'm looking to use
Do you want something like this?
comp = {}
comp.__index = function(obj,val)
if val == "insert" then
return rawget(obj,"gr"):insert(val)
end
return rawget(obj, val)
end
__index works just fine; it's because your last call is interpreted as:
pru.insert(pru, display.newImage("wakatuBlue.png"))
whereas you want/need it to be:
pru.insert(pru.gr, display.newImage("wakatuBlue.png"))
You either need to call it like this or explain what you are trying to do.

_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