How do you Parse this String in Lua "1 2 3 4"? - lua

I am brand new to Lua from a pure VB.Net background. I have a large file of maplines that I need to iterate through. The data is in the form of:
;XX.XXX YY.YYY Name
;
[Airways]
58.50 -12.44 58.21 -13.73
58.21 -13.73 57.89 -15.02
57.89 -15.02 57.54 -16.30
57.54 -16.30 57.17 -17.58
57.17 -17.58 56.76 -18.84
56.76 -18.84 56.33 -20.10
56.33 -20.10 55.87 -21.35
54.33 -25.02 53.77 -26.22
I have tried this but keep getting an error.
local mapLines = {}
local filePath = system.pathForFile( "data.ini", system.DocumentsDirectory )
local file = io.open( filePath, "r" )
if file then
local contents = file:read( "*a" )
--print( "Contents of " .. filePath )
--print( contents )
io.close( file )
local t = display.newText( "Contents of ", 5, 80, nil, 16 );
t:setTextColor( 255, 255, 136, 255 );
local t = display.newText( filePath, 5, 100, nil, 10 );
t:setTextColor( 255, 255, 136, 255 );
local ylast = 130
for line in io.lines(filePath) do
local t = display.newText( line, 15, ylast, nil, 14 );
t:setTextColor( 255, 255, 255 );
ylast = ylast + 20
n = tonumber(line);
if n == nil then
local f = {}
s = "1 2 3 4"
for k, v in string.gmatch(s, "(%w+) (%w+)") do
f[k] = v
end
local myLine = newLine(tonumber(f[1]), tonumber(f[2]), tonumber(f[3]), tonumber(f[4]))
table.insert( mapLines, myLine )
end
end
end
-- Example of shape drawing func
local function newLine(x,y,x1,y1)
-- need initial segment to start
local Line = display.newLine( x, y, x1, y1 )
Line:setColor( 30, 155, 30, 100 )
Line.width = 3
return Line
end
Runtime:addEventListener( "enterFrame", mapLines )
Any help would be greatly appreciated!
Dave

answering the question in the topic:
local string_to_parse = '1 2 3 4'
for s in string_to_parse:gmatch('%d+') do
print(s)
end
sample code on codepad

Related

GLua - part of the string library

I have gui wherein I need show information from table
When I open gui, I have this error:
"attempt to index a string value with bad key ('Index' is not part of the string library)"
SH file. In this file I put table information
MyList = {}
MyList = {
Index = 1,
Name = "Name 1",
Class = "exampleclass",
Description = "Desc 1",
Model = "modelname",
Color = Color(255, 255, 255, 255)
}
CL file. This file contains the part of the code where the error occurs. The error occurs on the first line
for k, v in SortedPairsByMemberValue( MyList, "Index" ) do
if v.Class == "exampleclass" then
local mainbuttons = vgui.Create( "DCollapsibleCategory", category )
mainbuttons:Dock(TOP)
mainbuttons:DockMargin(0, 6, 0, 2)
mainbuttons.Header:SetTall(24)
mainbuttons:SetExpanded(0)
mainbuttons:SetLabel("")
mainbuttons.Text = v.Name
function mainbuttons:Paint(w, h)
local h = 24
surface.SetDrawColor(v.Color)
surface.DrawRect(0, 0, w, h)
surface.SetFont("NovuxFont.ArialLight.16")
local textw, texth = surface.GetTextSize(self.Text)
surface.SetTextColor(Color(255, 255, 255))
surface.SetTextPos(16, h / 2 - texth / 2)
surface.DrawText(self.Text)
end
local craftpanel = vgui.Create( "DPanel", mainbuttons )
craftpanel:SetPos( 0, 25 )
craftpanel:SetSize( mainframescroll:GetWide(), 250 )
craftpanel.Paint = function() -- Paint function
surface.SetDrawColor( 65, 65, 65, 0 )
surface.DrawRect( 0, 0, craftpanel:GetWide(), craftpanel:GetTall() )
end
local spoilertext = vgui.Create( "DLabel", mainbuttons )
spoilertext:SetText( v.Description )
spoilertext:SetTextColor( Color( 255, 255, 255 ) )
spoilertext:SetFont( "NovuxFont.ArialLight.16" )
spoilertext:SetPos( 108, 32 )
spoilertext:SetSize( mainframescroll:GetWide(), 25 )
spoilertext.Paint = function( self, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color( 102, 102, 102, 0 ))
end
local modelframe = vgui.Create( "DModelPanel", mainbuttons )
modelframe:SetPos( 0, 65 )
modelframe:SetSize( 300, 200 )
modelframe:SetModel( v.Model )
modelframe:GetEntity():SetAngles( Angle( -10, 0, 15 ) )
local mn, mx = modelframe.Entity:GetRenderBounds()
local size = 0
size = math.max( size, math.abs( mn.x ) + math.abs( mx.x ) )
size = math.max( size, math.abs( mn.y ) + math.abs( mx.y ) )
size = math.max( size, math.abs( mn.z ) + math.abs( mx.z ) )
modelframe:SetFOV( 45 )
modelframe:SetCamPos( Vector( size, size, size ) )
modelframe:SetLookAt( (mn + mx) * 0.5 )
function modelframe:LayoutEntity( Entity )
return
end
end
end
The problem is that you put the whole item in MyList where by logic of SortedPairsByMemberValue you supposed to put new table inside MyList.
This fixes the problem:
MyList = {
{
Index = 1,
Name = "Name 1",
Class = "exampleclass",
Description = "Desc 1",
Model = "modelname",
Color = Color(255, 255, 255, 255)
}
}
Notice that now this is a nested table.

What is the best way to save and load variables?

I have a bunch of variables like "Upgrades bought", "Amount of money" etc.
I want the most efficient way to save these variables and load them upon starting the game, as you never even exited the game (every single thing stays the same).
So, all the settings and variables stay the same, until you reset the game.
I am asking since I think this is a huge and really important part and I want to begin with the best technique.
What are your suggestions and how can I implement that in my game?
You can store them as table fields and then serialize the table using one of the many options for serializers. See also the Serialization chapter in Programming in Lua.
There are two ways to do fairly easily:
Using a simple text file saved to your DocumentDirectory:
local filePath = system.pathForFile( "data.txt", system.DocumentsDirectory )
local file = io.open( filePath, "r" )
if file then
-- read all contents of file into a string
local contents = file:read( "*a" )
print( "Contents of " .. filePath )
print( contents )
io.close( file )
local t = display.newText( "Contents of ", 5, 80, nil, 16 );
t:setFillColor( 1, 1, 136/255 );
local t = display.newText( filePath, 5, 100, nil, 10 );
t:setFillColor( 1, 1, 136/255 );
local ylast = 130
for line in io.lines(filePath) do
local t = display.newText( line, 15, ylast, nil, 14 );
t:setFillColor( 1, 1, 1 );
ylast = ylast + 20
end
else
print( "Creating file..." )
-- create file b/c it doesn't exist yet
file = io.open( filePath, "w" )
file:write( "Feed me data!\n" )
local numbers = {1,2,3,4,5,6,7,8,9}
file:write( numbers[1], numbers[2], numbers[3], "\n" )
for _,v in ipairs( numbers ) do
file:write( v, " " )
end
file:write( "\nNo more data\n" )
io.close( file )
local t = display.newText( "Created file at:", 5, 80, nil, 16 );
t:setFillColor( 1, 1, 136/255 );
local t = display.newText( filePath, 5, 100, nil, 10 );
t:setFillColor( 1, 1, 136/255 );
local t = display.newText( "Run app again to test file read.", 5, 130, nil, 12 );
t:setFillColor( 1, 1, 136/255 );
-- This removes the file just created
-- os.remove( filePath )
end
2) Using a sqlite file saved to your DocumentDirectory:
--Include sqlite
require "sqlite3"
--Open data.db. If the file doesn't exist it will be created
local path = system.pathForFile("data.db", system.DocumentsDirectory)
db = sqlite3.open( path )
--Handle the applicationExit event to close the db
local function onSystemEvent( event )
if( event.type == "applicationExit" ) then
db:close()
end
end
--Setup the table if it doesn't exist
local tablesetup = [[CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, content, content2);]]
print(tablesetup)
db:exec( tablesetup )
--Add rows with a auto index in 'id'. You don't need to specify a set of values because we're populating all of them
local testvalue = {}
testvalue[1] = 'Hello'
testvalue[2] = 'World'
testvalue[3] = 'Lua'
local tablefill =[[INSERT INTO test VALUES (NULL, ']]..testvalue[1]..[[',']]..testvalue[2]..[['); ]]
local tablefill2 =[[INSERT INTO test VALUES (NULL, ']]..testvalue[2]..[[',']]..testvalue[1]..[['); ]]
local tablefill3 =[[INSERT INTO test VALUES (NULL, ']]..testvalue[1]..[[',']]..testvalue[3]..[['); ]]
db:exec( tablefill )
db:exec( tablefill2 )
db:exec( tablefill3 )
--print the sqlite version to the terminal
print( "version " .. sqlite3.version() )
--print all the table contents
for row in db:nrows("SELECT * FROM test") do
local text = row.content.." "..row.content2
local t = display.newText(text, 20, 120 + (20 * row.id), native.systemFont, 16)
t:setFillColor(1,0,1)
end
You can also use a cloud based which is virtually the same thing with more mobility.

Writing to a file from a TextBox Lua

Lately Ive been trying to make a basic word added. I want to make it so you tap on the text field and then you type what you need then it writes it to a .txt file (precreated or not) Im not great with coding and Im struggling to use the samples/other peoples Stack Exchange question to learn off. All I have is bits of code that dont work together and im not sure what I need to do to make them work (the code isnt mine)
local textBox = native.newTextBox( 200, 200, 280, 140 )
textBox.text = "This is line 1.\nAnd this is line2"
textBox.isEditable = true
local file = io.open( filePath, "r" )
if file then
-- read all contents of file into a string
local contents = file:read( "*a" )
print( "Contents of " .. filePath )
print( contents )
io.close( file ) -- Important to close (python knowledge)
local t = display.newText( "Contents of ", 5, 80, nil, 16 ); -- w, h, ?, size
t:setFillColor( 1, 1, 135/255 ); -- edit
local t = display.newText( filePath, 5, 100, nil, 10 );
t:setFillColor( 1, 1, 135/255 );
local ylast = 130 -- how far down the Y value it can make words on the screen
for line in io.lines(filePath) do
local t = display.newText ( line, 15, ylast, nil, 14); -- dont understand
t:setFillColor( 1, 1, 1 );
ylast = ylast + 20
end
end
local function inputListener( event )
if event.phase == "began" then
-- user begins editing textBox
print( event.text )
elseif event.phase == "ended" then
textBox.text = event.text
local path = system.pathForFile( "myfile.txt", system.DocumentsDirectory )
local file = io.open( path, "w" )
file:write( textBox.text )
io.close( file )
file = nil
elseif event.phase == "editing" then
print( event.newCharacters )
print( event.oldText )
print( event.startPosition )
print( event.text )
end
end
textBox:addEventListener( "userInput", inputListener )
I suggest using the loadsave functions it makes it easier.
You can download these functions from here.
https://github.com/robmiracle/Simple-Table-Load-Save-Functions-for-Corona-SDK
Once downloaded just drop the loadsave.lua file into your main project folder.
Now you can use it like this.
Example:
local loadsave = require("loadsave")
local tableToSave = {}
-- load text into a table
tableToSave ['saved-text'] = textYouWantToSave
-- save text
loadsave.saveTable(tableToSave, "filename.json")
local savedTable = {}
-- load text
savedTable = loadsave.loadTable("filename.json")
-- text is stored here
savedTable['saved-text']

how to go back in lua file from another lua file?

I have a menu lua and when i choose 1 of the category (the "songselect" lua) and go back to the menu lua i got this error:
Runtime error
...ocuments\corona projects\singingbeemenu\director.lua:151: attempt to
call field 'unloadMe' (a nil value)
stack traceback:
[C]: in function 'unloadMe'
...ocuments\corona projects\singingbeemenu\director.lua:151: in function
'_listener
'
this is 1 of my category the songselect.lua
module(..., package.seeall)
display.setStatusBar( display.HiddenStatusBar )
function new()
local localGroup = display.newGroup()
local tableView = require("tableView")
local ui = require("ui")
--------------------------------------------------------------------------
local screenOffsetW, screenOffsetH = display.contentWidth - display.viewableContentWidth, display.contentHeight - display.viewableContentHeight
local songList
local backBtn
local detailScreenText
local background = display.newRect(0, 0, display.contentWidth, display.contentHeight)
background:setFillColor(0, 0, 0)
local data = {}
--iPad: setup a color fill for selected items
local selected = display.newRect(0, 0, 50, 50) --add acolor fill to show the selected item
selected:setFillColor(67,141,241,180) --set the color fill to light blue
selected.isVisible = false --hide color fill until neede
-----------------------------------------------
data[1] = {}
data[1].title = "Crazy Song"
data[1].subtitle = "by Bruno Earth"
data[1].image = "note.png"
data[2] = {}
data[2].title = "Enter Sunman"
data[2].subtitle = "by Mentalica"
data[2].image = "note.png"
local topBoundary = display.screenOriginY + 40
local bottomBoundary = display.screenOriginY + 0
songList = tableView.newList{
data=data,
default="listItemBg.png",
over="listItemBg_over.png",
top=topBoundary,
bottom=bottomBoundary,
callback = function( row )
local g = display.newGroup()
local img = display.newImage(row.image)
g:insert(img)
img.x = math.floor(img.width*0.5 + 6)
img.y = math.floor(img.height*0.5)
local title = display.newText( row.title, 0, 0, native.systemFontBold, 16 )
title:setTextColor(0,0,0)
g:insert(title)
title.x = title.width*0.5 + img.width + 6
title.y = 30
local subtitle = display.newText( row.subtitle, 0, 0, native.systemFont, 14 )
subtitle:setTextColor(80,80,90)
g:insert(subtitle)
subtitle.x = subtitle.width*0.5 + img.width + 6
subtitle.y = title.y + title.height + 6
return g
end
}
local function scrollToTop()
songList:scrollTo(topBoundary-1)
end
local navBar = display.newImage("navBar.png")
navBar.x = display.contentWidth*.5
navBar.y = math.floor(display.screenOriginY + navBar.height*0.5)
local navHeader = display.newText("Song Lists", 0, 0, native.systemFontBold, 16)
navHeader:setTextColor(255, 255, 255)
navHeader.x = display.contentWidth*.5
navHeader.y = navBar.y
--Setup the back button
local backToMenu = function(event)
print (event.phase)
if event.phase == 'ended' then
print ("ok")
director:changeScene(event.target.scene, "fade")
print ("back!")
end
end
backBtn = display.newImage("backButton.png")
backBtn.x = math.floor(backBtn.width/2) + backBtn.width + screenOffsetW
backBtn.y = navBar.y
backBtn.scene = "menu"
backBtn:addEventListener("touch", backToMenu)
--backBtn.alpha = 0
local listBackground = display.newRect( 0, 0, songList.width, songList.height )
listBackground:setFillColor(255,255,255)
songList:insert(1,listBackground)
return localGroup
end
is it impossible the go back method in lua?
can anyone can help me and give an idea why i got the error?
thanks in advance...
I got this, i change my director.lua to the latest version...
Try this Lua file to solve your problem.

Corona: Can't get instance to "jump" on screen touch

Trying to get a sprite (instance1) to jump on touch, but it won't work.
Here is my code:
physics.addBody( instance1, { density=1.0, friction=0.3, bounce=0.3} )
local function jump( event )
if(event.numTaps == 2) then
instance1:applyForce( 350, -2000, instance1.x, instance1.y )
end
end
instance1:addEventListener("tap", jump)
I will add, that if I do this, the sprite instance will jump once, but never again:
local function jump( event )
if(event.numTaps == 2) then
physics.addBody( instance1, { density=1.0, friction=0.3, bounce=0.3} )
instance1:applyForce( 350, -2000, instance1.x, instance1.y )
end
end
instance1:addEventListener("tap", jump)
Instance info:
local sheet1 = sprite.newSpriteSheet( "character.png", 75, 105 )
local spriteSet1 = sprite.newSpriteSet(sheet1, 1, 16)
sprite.add( spriteSet1, "character", 1, 12, 700, 1 ) -- play 12 frames every 700 ms
local instance1 = sprite.newSprite( spriteSet1 )
instance1.x = display.contentWidth/2
instance1.y = 240
still cant reproduce your error,
i answered your question to paste the code i tested:
--main.lua
local sprite=require("sprite")
local physics=require("physics")
local sheet1 = sprite.newSpriteSheet( "character.png", 75, 105 )
local spriteSet1 = sprite.newSpriteSet(sheet1, 1, 16)
sprite.add( spriteSet1, "character", 1, 12, 700, 1 ) -- play 12 frames every 700 ms
local instance1 = sprite.newSprite( spriteSet1 )
instance1.x = display.contentWidth/2
instance1.y = 240
physics.start()
physics.setGravity(0,1)
physics.addBody( instance1, { density=1.0, friction=0.3, bounce=0.3} )
local function jump( event )
if(event.numTaps == 2) then
instance1:applyForce( 35, -200, instance1.x, instance1.y )
end
end
instance1:addEventListener("tap", jump)

Resources