I'm new to parse and I have a problem with the score column on my parse.com table called User.
Here is have my login function and after the users log in successfully, I have this function that is supposed to update the score while the user plays.
local parse = require( "mod_parse" )
local ego = require "ego"
local saveFile = ego.saveFile
local loadFile = ego.loadFile
--------------------------------------------------------------------
--------------------------------------------------------------------
_G.score = 1
_G.highscore = loadFile ("highscores.txt")
local function checkForFile ()
if highscore == "empty" then
highscore = 0
saveFile("highscores.txt", highscore)
end
end
checkForFile()
--Print the current highscore
print ("Highscore is", highscore)
-----------------------------------------------
dataTable = { ["score"] = tonumber(highscore) }
function onSystemEvent (event)
if _G.score > tonumber(_G.highscore) then --We use tonumber as highscore is a string when loaded
saveFile("highscores.txt", _G.score)
parse:updateObject( "objectId", dataTable, onSystemEvent )
end
end
_G.timer1=timer.performWithDelay(100, addToScore, 0)
The functions compare the score with the highscore and if score is higher than the highscore updates highscore with the new value.
I'm having trouble with the parse:updateObject function. I have a column called score on parse that I'm trying to update with the new highscore. What am I doing wrong?
You're trying to save the object by calling the updateObject method, which I think requires you to know the objectID of the object you wish to save. I'm guessing that you tried to use "objectId", but that is certainly not the correct objectID. Farther than this, I can not help you as I do not know LUA.
I'm guessing you need some sort of ParseObject that you can save a new row. I recommend that you take a look at the Parse SDKs, they explain it very well.
Related
Im trying to add pictured menu ,but it gives me error.Error, .lua
function loadPlayerInventory()
TBCore.Functions.TriggerServerCallback('tb-inventory:server:getPlayerInventory', function(data)
items =
inventory = data.inventory
weapons = data.weapons
local weight = 0
if inventory ~= nil then
for k, v in pairs(inventory) do
table.insert(items, inventory[k])
weight = weight + (inventory[k].amount * inventory[k].weight)
end
items =
should give you an error "unexpected symbol near = So you should not even get to that point that your callback is called.
You forgot to assign a value to items. Your code suggests that it should be a table.
The error in the screenshot is caused by indexing data, a local nil value.
inventory = data.inventory
This is because your callback is called but no parameter data is given. Find out why or make sure you don't index it if it is nil.
Something like
if data then
inventory = data.inventory
end
or
inventory = data and data.inventory
for example
I'm currently starting work on a text adventure game in Lua--no addons, just pure Lua for my first project. In essence, here is my problem; I'm trying to find out how I can do a "reverse lookup" of a table using one of its variables. Here's an example of what I've tried to do:
print("What are you trying to take?")
bag = {}
gold = {name="Gold",ap=3}
x = io.read("*l")
if x == "Gold" then
table.insert(bag,gold)
print("You took the " .. gold.name .. ".")
end
Obviously, writing a line like this with every single object in the game would be very... exhausting--especially since I think I'll be able to use this solution for not just taking items but movement from room to room using a reverse lookup with each room's (x,y) coordinates. Anyone have any ideas on how to make a more flexible system that can find a table by the player typing in one of its variables? Thanks in advance!
-blockchainporter
This doesn't directly answer your question as you asked it, but I think it would serve the purpose of what you are trying to do. I create a table called 'loot' which can hold many objects, and the player can place any of these in their 'bag' by typing the name.
bag = {}
loot = {
{name="Gold", qty=3},
{name="Axe", qty=1},
}
print("What are you trying to take?")
x = io.read("*l")
i = 1
while loot[i] do
if (x == loot[i].name) then
table.insert(bag, table.remove(loot,i))
else
i = i + 1
end
end
For bonus points, you could check 'bag' to see if the player has some of that item already and then just update the quantity...
while loot[i] do
if (x == loot[i].name) then
j, found = 1, nil
while bag[j] do
if (x == bag[j].name) then
found = true
bag[j].qty = bag[j].qty + loot[i].qty
table.remove(loot,i)
end
j = j + 1
end
if (not found) then
table.insert(bag, table.remove(loot,i))
end
else
i = i + 1
end
end
Again, this isn't a 'reverse lookup' solution like you asked for... but I think it is closer to what you are trying to do by letting a user choose to loot something.
My disclaimer is that I don't use IO functions in my own lua usage, so I have to assume that your x = io.read("*l") is correct.
PS. If you only ever want objects to have a name and qty, and never any other properties (like condition, enchantment, or whatever) then you could also simplify my solution by using key/val pairs:
bag = {}
loot = { ["Gold"] = 3, ["Axe"] = 1 }
print("What are you trying to take?")
x = io.read("*l")
for name, qty in pairs(loot) do
if x == name then
bag.name = (bag.name or 0) + qty
loot.name = nil
end
end
I have a few notes to start before I specifically address your question. (I just want to do this before I forget, so please bear with me!)
I recommend printing to the terminal using stderr instead of stdout--the Lua function print uses the latter. When I am writing a Lua script, I often create a C-style function called eprintf to print formatted output to stderr. I implement it like this:
local function eprintf(fmt, ...)
io.stderr:write(string.format(fmt, ...))
return
end
Just be aware that, unlike print, this function does not automatically append a newline character to the output string; to do so, remember to put \n at the end of your fmt string.
Next, it may be useful to define a helper function that calls io.read("*l") to get an entire line of input. In writing some example code to help answer your question, I called my function getline--like the C++ function that has similar behavior--and defined it like this:
local function getline()
local read = tostring(io.read("*l"))
return read
end
If I correctly understand what it is you are trying to do, the player will have an inventory--which you have called bag--and he can put items into it by entering item names into stdin. So, for instance, if the player found a treasure chest with gold, a sword, and a potion in it and he wanted to take the gold, he would type Gold into stdin and it would be placed in his inventory.
Based on what you have so far, it looks like you are using Lua tables to create these items: each table has a name index and another called ap; and, if a player's text input matches an item's name, the player picks that up item.
I would recommend creating an Item class, which you could abstract nicely by placing it in its own script and then loading it as needed with require. This is a very basic Item class module I wrote:
----------------
-- Item class --
----------------
local Item = {__name = "Item"}
Item.__metatable = "metatable"
Item.__index = Item
-- __newindex metamethod.
function Item.__newindex(self, k, v)
local err = string.format(
"type `Item` does not have member `%s`",
tostring(k)
)
return error(err, 2)
end
-- Item constructor
function Item.new(name_in, ap_in)
assert((name_in ~= nil) and (ap_in ~= nil))
local self = {
name = name_in,
ap = ap_in
}
return setmetatable(self, Item)
end
return Item
From there, I wrote a main driver to encapsulate some of the behavior you described in your question. (Yes, I know my Lua code looks more like C.)
#!/usr/bin/lua
-------------
-- Modules --
-------------
local Item = assert(require("Item"))
local function eprintf(fmt, ...)
io.stderr:write(string.format(fmt, ...))
return
end
local function printf(fmt, ...)
io.stdout:write(string.format(fmt, ...))
return
end
local function getline()
local read = tostring(io.read("*l"))
return read
end
local function main(argc, argv)
local gold = Item.new("Gold", 3)
printf("gold.name = %s\ngold.ap = %i\n", gold.name, gold.ap)
return 0
end
main(#arg, arg)
Now, as for the reverse search which you described, at this point all you should have to do is check the user's input against an Item's name. Here it is in the main function:
local function main(argc, argv)
local gold = Item.new("Gold", 3)
local bag = {}
eprintf("What are you trying to take? ")
local input = getline()
if (input == gold.name) then
table.insert(bag, gold)
eprintf("You took the %s.\n", gold.name)
else
eprintf("Unrecognized item `%s`.\n", input)
end
return 0
end
I hope this helps!
I have a function, which changes the variable from what it was to something new. I am using load-save .json tables to get and load data. How do I update the startmoneyTxt to display the new variable?
My function:
local function unlockBall(event)
ballfirst = loadsave.loadTable("firstBall.json", system.DocumentsDirectory)
currentMoney1 = loadsave.loadTable("cashTable.json", system.DocumentsDirectory)
difference = currentMoney1 - ballfirstUnlock
if(ballfirst == 0 and difference >= 0)then
ballfirstID = 1
loadsave.saveTable(ballfirstID, "firstBall.json", system.DocumentsDirectory)
loadsave.saveTable(difference, "cashTable.json", system.DocumentsDirectory)
end
end
My code which should be updated:
currentMoney = loadsave.loadTable("cashTable.json", system.DocumentsDirectory)
startmoneyTxt= display.newText("$ "..currentMoney.." " , 0,0, "Helvetica", 20)
sceneGroup:insert(startmoneyTxt)
Whenever you want change text use
startmoneyTxt.text = "Your text here"
Note: As names saveTable and loadTable imply functions are indent to save/load tables. So you can use one file to save/load multiple values.
I use loadsave module to save/load setings in my game The Great Pong.
I seem to be having an issue with my database in corona sdk. I want to store the play counts every time a player plays the game. my project doesn't have a gamescene and plays only through menu.lua. I have set up a highscore database (which is separate from the other one but exactly the same) and it works fine and updates/loads data fine. My play count data base however doesn't work.
At first the play count increases by 1 when the game returns to menu again once its removed. But tries after that doesn't increase the value, it's like it has reset.
Globals.lua
M.plays = 0
--------------------------
local function setupDatabase2()
local dbPath = system.pathForFile("appInfo.db3", system.DocumentsDirectory)
local db = sqlite3.open( dbPath )
local tablesetup1 = [[
CREATE TABLE played (id INTEGER PRIMARY KEY, plays);
INSERT INTO played VALUES (NULL, '0');
]]
db:exec( tablesetup1 ) --Create it now.
db:close() --Then close the database
end
setupDatabase2()
M.loadAppInfo = function()
local dbPath = system.pathForFile("appInfo.db3", system.DocumentsDirectory)
local db = sqlite3.open(dbPath)
for row in db:nrows("SELECT * FROM played WHERE id = 1") do
M.plays = tonumber(row.plays)
end
db:close()
end
M.saveAppInfo = function()
local dbPath = system.pathForFile("appInfo.db3", system.DocumentsDirectory)
local db = sqlite3.open(dbPath)
local update = "UPDATE played SET plays='" .. M.plays .."' WHERE id=1"
db:exec(update)
db:close()
end
return M
menu.lua
local utils = require("helpers.globals")
local play = 0
----------------------------------------
function scene:createScene( event )
local group = self.view
utils.loadHighscoreInfo() -- Separate db which is working fine
utils.loadAppInfo()
function beginGame( event )
timerSrc = timer.performWithDelay(400, createBlock, -1)
Runtime:addEventListener("enterFrame", gameLoop)
play = play +1
utils.plays = play
utils.saveAppInfo()
end
Your SQL statement is doing all of that. Your current sql creates a table everytime it is called. Try this:
local tablesetup1 = [[
CREATE TABLE IF NOT EXISTS played (id INTEGER PRIMARY KEY, plays);
INSERT INTO played VALUES (NULL, '0');]]
I guess that statement is pretty much self explanatory :)
How would I code a function to iterate through one "pages" worth of data? Sample code would be ideal...
So say we image the size of a page is 5 items. If we had a lua table with 18 items it would need to print out:
Page 1: 1 to 5
Page 2: 6 to 10
Page 3: 11 to 15
Page 4: 16 to 18
So assume the data is something like:
local data = {}
data["dog"] = {1,2,3}
data["cat"] = {1,2,3}
data["mouse"] = {1,2,3}
data["pig"] = {1,2,3}
.
.
.
How would one code the function that would do the equivalent of this:
function printPage (myTable, pageSize, pageNum)
-- find items in "myTable"
end
So in fact I'm not even sure if a Lua table used as a dictionary can even do this? There is no specific ordering is there in such a table, so how would you be sure the order would be the same when you come back to print page 2?
The next function allows you to go through a table in an order (albeit an unpredictable one). For example:
data = { dog = "Ralf", cat = "Tiddles", fish = "Joey", tortoise = "Fred" }
function printPage(t, size, start)
local i = 0
local nextKey, nextVal = start
while i < size and nextKey ~= nil do
nextKey, nextVal = next(t, nextKey)
print(nextKey .. " = " .. nextVal)
i = i + 1
end
return nextKey
end
local nextPage = printPage(data, 2) -- Print the first page
printPage(data, 2, nextPage) -- Print the second page
I know this isn't quite in the form you were after, but I'm sure it can be adapted quite easily.
The next function returns the key after the one provided in the table, along with its value. When the end of the table is reached, it returns nil. If you provide nil as the second parameter, it returns the first key and value in the table. It's also documented in Corona, although it appears to be identical.