XmlParser in Gideros with Lua - lua

I'm working with Gideros and I got the error but I don't know why and how to fix.
The error is:
attempt to index local 'xml_layout_x'
My build: http://www.mediafire.com/download/utowfooin439b66/Ex2.zip
This is my header.xml
<rss version="2.0">
<layout>
<layout_x>35</layout_x>
<layout_y>150</layout_y>
<layout_width>825</layout_width>
<image>
<width>270</width>
<height>240</height>
</image>
<table>
<layout_x>25</layout_x>
<tablerow
textview_name=".Name:"
edittext_name_height="18"
edittext_name_width="245"
edittext_name_offset_x="150"
textview_born=".Born:"
textview_weight=".Weight:"
textview_bio=".Bio:"
edittext_bio_width="441"
edittext_bio_height="71"
/>
</table>
<action>
<name>update</name>
</action>
<file:path bio="bio_001.txt" image="Avatar_001.png"/>
<file:path bio="bio_002.txt" image="Avatar_002.png"/>
</layout>
</rss>
Then, it's my code
local function getChild(xml, name)
for i=1,#xml.ChildNodes do
if xml.ChildNodes[i].Name == name then
return xml.ChildNodes[i]
end
end
end
-- helper function to get all children of xml node by name
local function getChildren(xml, name)
local result = {}
for i=1,#xml.ChildNodes do
if xml.ChildNodes[i].Name == name then
result[#result + 1] = xml.ChildNodes[i]
end
end
return result
end
info = gideros.class(Sprite)
if info.innerSprite ~= nil then
info:removeChild(self.innerSprite)
end
info.innerSprite = Sprite.new()
info.innerSprite:setPosition(200, 10)
local font = TTFont.new("Roboto-Regular.ttf", 38)
local small_font = TTFont.new("Roboto-Regular.ttf", 30)
function info:init()
local xml = XmlParser:ParseXmlFile("header.xml")
local layout = getChild(xml, "layout")
local filepath = getChildren(layout, "file:path")
local logo = Bitmap.new(Texture.new("logo.png"))
self:addChild(logo)
logo:setPosition(780, 5)
local Update_Btn = Bitmap.new(Texture.new("Update_Btn.png"))
self:addChild(Update_Btn)
Update_Btn:setPosition(33, 23)
Update_Btn:addEventListener(Event.MOUSE_DOWN,
function()
-- Get source
local src_bio = {}
local src_image = {}
for i = 1, #filepath do
table.insert(src_bio, filepath[i].Attributes["bio"])
table.insert(src_image, filepath[i].Attributes["image"])
end
-- Check if file exist
for i = 1, #filepath do
local bio_file = io.open(src_bio[i])
local image_file = io.open(src_image[i])
if (bio_file == nil or image_file == nil) then
table.remove(src_bio, i)
table.remove(src_image, i)
else
bio_file:close()
image_file:close()
end
end
-- Get content
local tbInfo_List = {}
for i = 1, #src_bio do
tbInfo_List[i] = {}
local tbInfo_tmp1 = ReadFile(src_bio[i])
local tbInfo_tmp2 = ConvertTable(tbInfo_tmp1)
table.insert(tbInfo_List[i], tbInfo_tmp2)
end
-- Fill content
local xml_layout_x = getChild(layout, "layout_x") *=> the error is HERE*
local layout_x = xml_layout_x.Value
local xml_layout_y = getChild(layout, "layout_y")
local layout_y = xml_layout_y.Value
local xml_layout_width = getChild(layout, "layout_width")
local layout_width = xml_layout_width.Value
for i = 1, #tbInfo_List do
local tmp_y = layout_y + layout_width*(i - 1) + 25
table.insert(tbInfo_List[i], src_image[i])
CreateInformationTag(layout_x, tmp_y, tbInfo_List[i], layout)
end
end
)
local Exit_Btn = Bitmap.new(Texture.new("Exit_Btn.png"))
self:addChild(Exit_Btn)
Exit_Btn:setPosition(397, 23)
Exit_Btn:addEventListener(Event.MOUSE_DOWN,
function()
sceneManager:changeScene("home", 1, transition, easing.outBack)
end
)
end
local function CreateInformationTag(x,y, tbInfo, layout)
local image = Bitmap.new(Texture.new(tbInfo.image))
local name = tbInfo.name
local born = tbInfo.born
local weight = tbInfo.weight
local bio = tbInfo.bio
--Add Image
image.setPosition(x, y)
self.innerSprite.addChild(image)
local xml_image = getChild(layout, "image")
local xml_image_width = getChild(layout, "width")
local image_width = xml_image_width.Value()
local xml_table = getChild(layout, "table")
local xml_table_layout_x = getChild(xml_table, "layout_x")
local table_layout_x = xml_table_layout_x.Value()
local xml_table_row = getChild(xml_table, "tablerow")
local tbTextView = {}
-- .Name
local xml_table_row_textview_name = getChild(xml_table_row, "textview_name")
table.insert(tbTextView, xml_table_row_textview_name.Value())
-- .Born
local xml_table_row_textview_born = getChild(xml_table_row, "textview_born")
table.insert(tbTextView, xml_table_row_textview_born.Value())
-- .Weight
local xml_table_row_textview_weight = getChild(xml_table_row, "textview_weight")
table.insert(tbTextView, xml_table_row_textview_weight.Value())
-- .Bio
local xml_table_row_textview_bio = getChild(xml_table_row, "textview_bio")
table.insert(tbTextView, xml_table_row_textview_bio.Value())
local table_x = x + image_width + table_layout_x
local table_y = y
local table_offset_y = 20
-- Add label
for i = 1, 4 do
local textfield = TextField.new(font, tbTextView[i])
local tmp_y = table_y + (i - 1)*table_offset_y
textfield:setPosition(table_x, tmp_y)
self.innerSprite:addChild(textfield)
end
-- Add text box
local edittext_name_offset_x = getChild(xml_table_row, "edittext_name_offset_x")
local name_offset_x = edittext_name_offset_x.Value()
local edittext_name_width = getChild(xml_table_row, "edittext_name_width")
local name_width = edittext_name_width.Value()
local edittext_name_height = getChild(xml_table_row, "edittext_name_height")
local name_height = edittext_name_height.Value()
-- Draw text box
for i = 1, 3 do
local line = Shape.new()
local tmp_y = table_y + table_offset_y*(i - 1)
line:setLineStyle(5, 0x000000, 1)
line:beginPath()
line:moveTo(table_x + edittext_name_x,tmp_y)
line:lineTo(table_x + edittext_name_x + name_width, tmp_y)
line:lineTo(table_x + edittext_name_x + name_width, tmp_y + name_height)
line:lineTo(table_x + edittext_name_x, tmp_y + name_height)
line:lineTo(table_x + edittext_name_x, tmp_y)
line:endPath()
self.innerSprite:addChild(line)
end
-- Draw bio text box
local edittext_bio_width = getChild(xml_table_row, "edittext_bio_width")
local bio_width = edittext_bio_width.Value()
local edittext_bio_height = getChild(xml_table_row, "edittext_bio_height")
local bio_height = edittext_bio_height.Value()
local line_bio = Shape.new()
line_bio:setLineStyle(5, 0x000000, 1)
line_bio:beginPath()
line_bio:moveTo(table_x + edittext_name_x,tmp_y)
line_bio:lineTo(table_x + edittext_name_x + bio_width, tmp_y)
line_bio:lineTo(table_x + edittext_name_x + bio_width, tmp_y + bio_height)
line_bio:lineTo(table_x + edittext_name_x, tmp_y + bio_height)
line_bio:lineTo(table_x + edittext_name_x, tmp_y)
line_bio:endPath()
self.innerSprite:addChild(line_bio)
-- Add text in box
for i = 1, 3 do
local textfield = TextField.new(small_font, tbInfo[i])
local tmp_y = table_y + (i - 1)*table_offset_y
textfield:setPosition(table_x, tmp_y)
self.innerSprite:addChild(textfield)
end
-- Add wrap text
local tw = TextWrap2.new(tbInfo[4], table_x, table_y + 2*table_offset_y , 18, small_font)
self.innerSprite:addChild(tw)
end
function ReadFile(filename)
local tbInfo = {}
fp = io.open(filename, "r")
for line in fp:lines() do
table.insert(tbInfo, line)
end
fp:close()
return tbInfo
end
function ConvertTable(tbInfo)
local tmp = {}
for i = 1, #tbInfo do
if (i <= 4) then<br /> table.insert(tmp, tbInfo[i])
else
local str1 = tmp[5]
local str2 = tbInfo[i]
table.remove(tmp, 5)
local str = str1 + str2
table.insert(tmp, str)
end
end
return tmp
end

I solved the problem :D
The xml file causes the error when parsing. Thanks all

Related

Not doing the random pet, just giving the rarest every time. How do I fix it?

I am making a simulator game on roblox and it has a pet system. I revamped how the hatch works, and for some reason it started to glitch out, and always give the same pet, and the pet was always the rarest one. I don't know what the problem is, here is the script. The Weight system worked perfectly before, but now it isnt working. I compared it to the old version of the game and the only difference is what the variables are called.
game.ReplicatedStorage.OpenEgg.OnServerInvoke = (function(player, amount, egg)
print("Fired")
if not player:FindFirstChild("Debounce") then
if amount == "One" then
local CC = player.leaderstats.CloudCoins
local EO = player.leaderstats.EggsOpened
local EGGS = require(game.ReplicatedStorage.EGGS)
local Data = EGGS[egg]
local Price = Data["Cost"]
local Pets = Data["Pets"]
local TotalWeight = 0
for i,v in pairs(Pets) do
TotalWeight = TotalWeight + v[1]
end
local function ChoosePet(player)
local Chance = math.random(1,TotalWeight)
local Counter = 0
for d,c in pairs(Pets)do
Counter = Counter + c[1]
if Chance >= Counter then
return d
end
end
end
local function GetChance(ChosenPet)
for i, v in pairs(Pets)do
for o,b in pairs(Pets) do
if o == ChosenPet then
return b[1]
end
end
end
end
if CC.Value >= Price then
local ChosenPet = ChoosePet(player)
local Chance = GetChance(ChosenPet)
CC.Value = CC.Value - Price
EO.Value = EO.Value + 1
local Pet = Instance.new("BoolValue")
Pet.Name = ChosenPet
Pet.Parent = player.Pets
if not player.PetsA:FindFirstChild(Pet.Name.." Amount") then
local AmountA = Instance.new("IntValue")
AmountA.Name = Pet.Name.." Amount"
AmountA.Value = 1
else
local AmountA = player.PetsA[Pet.Name.." Amount"]
AmountA.Value = AmountA.Value + 1
end
local Level = Instance.new("IntValue")
local Xp = Instance.new("IntValue")
local Number = Instance.new("IntValue")
Number.Name = "Number"
Number.Value = player.PetsA[Pet.Name.." Amount"].Value
Number.Parent = Pet
Level.Name = "Level"
Xp.Name = "XP"
Level.Value = 1
Xp.Value = 0
Level.Parent = Pet
Xp.Parent = Pet
return("Hatched")
else
return("NotEnoughCoins")
end
end
if amount == "Triple" then
local CC = player.leaderstats.CloudCoins
local EO = player.leaderstats.EggsOpened
local EGGS = require(game.ReplicatedStorage.EGGS)
local Data = EGGS[egg]
local Price = Data["Cost"]
local Pets = Data["Pets"]
local TotalWeight = 0
for i,v in pairs(Pets) do
TotalWeight = TotalWeight + v[1]
end
local function ChoosePet(player)
local Chance = math.random(1,TotalWeight)
local Counter = 0
for d,c in pairs(Pets)do
Counter = Counter + c[1]
if Chance >= Counter then
return d
end
end
end
local function GetChance(ChosenPet)
for i, v in pairs(Pets)do
for o,b in pairs(Pets) do
if o == ChosenPet then
return b[1]
end
end
end
end
if CC.Value >= Price*3 then
local ChosenPet1,ChosenPet2,ChosenPet3 = ChoosePet(player),ChoosePet(player),ChoosePet(player)
local Chance1,Chance2,Chance3 = GetChance(ChosenPet1),GetChance(ChosenPet2),GetChance(ChosenPet3)
CC.Value = CC.Value - Price*3
EO.Value = EO.Value + 3
local Pet1 = Instance.new("BoolValue")
Pet1.Name = ChosenPet1
Pet1.Parent = player.Pets
local Level1 = Instance.new("IntValue")
local Xp1 = Instance.new("IntValue")
local Number1 = Instance.new("IntValue")
Number1.Name = "Number"
if not player.PetsA:FindFirstChild(Pet1.Name.." Amount") then
local AmountA = Instance.new("IntValue")
AmountA.Name = Pet1.Name.." Amount"
AmountA.Value = 1
else
local AmountA = player.PetsA[Pet1.Name.." Amount"]
AmountA.Value = AmountA.Value + 1
end
Number1.Value = player.PetsA[Pet1.Name.." Amount"].Value
Number1.Parent = Pet1
Level1.Name = "Level"
Xp1.Name = "XP"
Level1.Value = 1
Xp1.Value = 0
Level1.Parent = Pet1
Xp1.Parent = Pet1
local Pet2 = Instance.new("BoolValue")
Pet2.Name = ChosenPet2
Pet2.Parent = player.Pets
local Level2 = Instance.new("IntValue")
local Xp2 = Instance.new("IntValue")
local Number2 = Instance.new("IntValue")
Number2.Name = "Number"
if not player.PetsA:FindFirstChild(Pet2.Name.." Amount") then
local AmountA = Instance.new("IntValue")
AmountA.Name = Pet2.Name.." Amount"
AmountA.Value = 1
else
local AmountA = player.PetsA[Pet2.Name.." Amount"]
AmountA.Value = AmountA.Value + 1
end
Number2.Value = player.PetsA[Pet2.Name.." Amount"].Value
Number2.Parent = Pet2
Level2.Name = "Level"
Xp2.Name = "XP"
Level2.Value = 1
Xp2.Value = 0
Level2.Parent = Pet2
Xp2.Parent = Pet2
local Pet3 = Instance.new("BoolValue")
Pet3.Name = ChosenPet3
Pet3.Parent = player.Pets
local Level3 = Instance.new("IntValue")
local Xp3 = Instance.new("IntValue")
local Number3 = Instance.new("IntValue")
Number3.Name = "Number"
if not player.PetsA:FindFirstChild(Pet3.Name.." Amount") then
local AmountA = Instance.new("IntValue")
AmountA.Name = Pet3.Name.." Amount"
AmountA.Value = 1
else
local AmountA = player.PetsA[Pet3.Name.." Amount"]
AmountA.Value = AmountA.Value + 1
end
Number3.Value = player.PetsA[Pet3.Name.." Amount"].Value
Number3.Parent = Pet3
Level3.Name = "Level"
Xp3.Name = "XP"
Level3.Value = 1
Xp3.Value = 0
Level3.Parent = Pet3
Xp3.Parent = Pet3
return("Hatched")
else
return("NotEnoughCoins")
end
end
end
end)
take a closer look at these lines of code.
local TotalWeight = 0
for i,v in pairs(Pets) do
TotalWeight = TotalWeight + v[1]
end
local function ChoosePet(player)
local Chance = math.random(1,TotalWeight)
local Counter = 0
for d,c in pairs(Pets)do
Counter = Counter + c[1]
if Chance >= Counter then
return d
end
end
end
the next time we see this function it is to assign the chosen pet to the player. I would suggest playing around with the Chance value. Set it to something crazy and see if you get another pet instead.

"no such file or directory" in preloader

I'm making a preloader for a large application. Today the error occurred "no such file or directory". This error occurs only on Android device. On the computer(in the simulator) works fine. All file names and directories to lowercase.
Code:
---------------------------------------------
---------------- Прелоадер ------------------
-- Сервис по загрузке текстур, звука --------
---------------------------------------------
TEXTURES = {} -- место в оперативной памяти для текстур
SOUNDS = {} -- место в оперативной памяти для звука
local Preloader = {}
local path = {
animations = "assets/images/animations/",
army_run = "assets/images/animations/army_run/",
area = "assets/images/area/",
access = "assets/images/area/access/",
artefacts = "assets/images/artefacts/",
castles = "assets/images/building/castles/",
mining = "assets/images/building/mining/",
flags = "assets/images/flags/",
interface = "assets/images/interface/",
marker = "assets/images/interface/marker/",
items = "assets/images/items/",
raw = "assets/images/raw/",
}
-- Место для путей к текстурам
Preloader.texture = {}
-- Место для путей к звуку
Preloader.sound = {}
-- Загрузка текстур в оперативную память
Preloader.loadingTextures = function(arr)
TEXTURES[arr.id] = {}
for i = 1, #arr do
local name = string.gsub(arr[i], '.*(.*)/', '')
TEXTURES[arr.id][name] = graphics.newTexture( { type="image", filename = arr[i] } )
TEXTURES[arr.id][name]:preload()
end
end
-- Загрузка звука в оперативную память
Preloader.loadingSounds = function()
for i = 1, #Preloader.sound do
sounds[Preloader.sound[i]] = audio.loadSound( "snd/"..Preloader.sound[i] )
end
end
-- Таймер
Preloader.getTimer = function()
return system.getTimer()
end
-- Окно загрузки
Preloader.screenLoader = nil
Preloader.loaderShow = function()
if(Preloader.screenLoader)then
return false
end
Preloader.screenLoader = display.newGroup()
Preloader.screenLoader.x = _W/2
Preloader.screenLoader.y = _H/2
local screen = display.newRect( 0, 0, _W, _H )
screen:setFillColor( 0, 0, 0 )
Preloader.screenLoader:insert(screen)
local imgLoad = "assets/images/animations/army_run/150.png"
local sheetLoad = graphics.newImageSheet( imgLoad, { width = 224, height = 224, numFrames = 8 } )
local animLoad = display.newSprite( Preloader.screenLoader, sheetLoad, { start = 1, count = 8, time = 800, loopCount=0 } )
animLoad.xScale, animLoad.yScale = _H*.001, _H*.001
animLoad.x, animLoad.y = 0, _H*-.07
animLoad:play()
-- Загрузка в процентах
tfLoader = display.newText( TEXTS.Preloader.loading..": 0%", 0, _H*.08, font, _H*.035 )
tfLoader:setTextColor( 1,1,1)
Preloader.screenLoader:insert(tfLoader)
Preloader.screenLoader.tf = tfLoader
-- Загрузка в этапах
stepLoader = display.newText( TEXTS.Preloader.start_load, 0, _H*.125, font, _H*.022 )
stepLoader:setTextColor( 160/255, 160/255, 160/255 )
Preloader.screenLoader:insert(stepLoader)
Preloader.screenLoader.step = stepLoader
end
-- Создание массивов с путями
Preloader.createPath = function()
for k, v in pairs(path) do
local i = 0
Preloader.texture[k] = { id = k }
for l in lfs.dir(v) do
if ( l ~= "." and l ~= ".." and l ~= "..." ) then
i = i + 1
Preloader.texture[k][i] = v..l
end
end
end
end
-- Запуск прелоадера и контроль процесса загрузки
Preloader.start = function()
-- Создаём шаги для загрузки
local loading_steps = {}
-- Шаг 1 - Загрузка путей
table.insert(loading_steps, function()
Preloader.createPath()
Preloader.screenLoader.step.text = TEXTS.Preloader.path_load..'...'
end)
-- Шаг 2 - Загрузка текстур интерфейса
table.insert(loading_steps, function()
Preloader.loadingTextures(Preloader.texture.interface)
Preloader.loadingTextures(Preloader.texture.marker)
Preloader.screenLoader.step.text = TEXTS.Preloader.interface_load..'...'
end)
-- Шаг 3 - Загрузка анимаций
table.insert(loading_steps, function()
Preloader.loadingTextures(Preloader.texture.animations)
Preloader.loadingTextures(Preloader.texture.army_run)
Preloader.screenLoader.step.text = TEXTS.Preloader.animations_load..'...'
end)
-- Шаг 4 - Создание карты
table.insert(loading_steps, function()
Preloader.loadingTextures(Preloader.texture.area)
Preloader.loadingTextures(Preloader.texture.access)
Preloader.loadingTextures(Preloader.texture.castles)
Preloader.loadingTextures(Preloader.texture.mining)
Preloader.screenLoader.step.text = TEXTS.Preloader.map_load..'...'
end)
-- Шаг 5 - Загрузка ресурсов
table.insert(loading_steps, function()
Preloader.loadingTextures(Preloader.texture.raw)
Preloader.loadingTextures(Preloader.texture.items)
Preloader.loadingTextures(Preloader.texture.artefacts)
Preloader.screenLoader.step.text = TEXTS.Preloader.res_load..'...'
end)
-- Шаг 6 - Загрузка параметров игрока
table.insert(loading_steps, function()
Preloader.loadingTextures(Preloader.texture.flags)
Preloader.screenLoader.step.text = TEXTS.Preloader.res_load..'...'
end)
local loading_steps_max = #loading_steps+1
local st = Preloader.getTimer()
Preloader.loaderShow()
local function mainHandler(e)
if(#loading_steps>0)then
loading_steps[1]()
table.remove(loading_steps, 1)
if(Preloader.screenLoader)then
local loading_p = math.floor((loading_steps_max - #loading_steps)*100/loading_steps_max)
Preloader.screenLoader.tf.text = TEXTS.Preloader.loading..': '..loading_p..'%'
end
return true
end
Preloader.loaderClose()
print('Time load: '..(Preloader.getTimer()-st)..'ms')
Runtime:removeEventListener("enterFrame", mainHandler)
end
Runtime:addEventListener("enterFrame", mainHandler)
end
-- Окончание загрузки
Preloader.loaderClose = function()
if(Preloader.screenLoader)then
if(Preloader.screenLoader.removeSelf)then
Preloader.screenLoader:removeSelf()
end
end
Preloader.screenLoader = nil
-- Переход на стартовую сцену
composer.gotoScene( start_scene, "fade", 0 )
end
-- Сборщик мусора
Preloader.garbage_collector = function()
for key in pairs(TEXTURES) do
for i=1, #TEXTURES[key] do
TEXTURES[key][i]:releaseSelf()
end
end
TEXTURES = {}
end
return Preloader
That's how I show images on stage:
M.dial = display.newImageRect( M.gr, TEXTURES.interface["btn_compas_comp.png"].filename, TEXTURES.interface["btn_compas_comp.png"].baseDir, 272, 272 )
M.dial.x, M.dial.y = X, Y
Thanks in advance friends.
1) All file names and directories to lowercase - I suggest to double-check this because Android filesystem is case sensitive.
2) Also check your build.settings to ensure that excludeFiles section doesn't include any of directories from your code
Edit: Another idea based on corona lfs doc - try following before loading:
local resourcesPath = system.pathForFile( "", system.ResourceDirectory )
-- Change current working directory
local success = lfs.chdir( resourcesPath ) --returns true on success
I guess that lfs doesn't point on resource directory by default. All your assets should be in this directory, but don't try to modify them - For security reasons, this directory is read-only and enforced by the operating system, not by Corona.
Edit 2: Solution that don't rely on current directory
Preloader.createPath = function()
for k, v in pairs(path) do
local i = 0
local pathForDirectory = system.pathForFile(v, system.ResourceDirectory)
Preloader.texture[k] = { id = k }
for l in lfs.dir(pathForDirectory) do
if ( l ~= "." and l ~= ".." and l ~= "..." ) then
i = i + 1
Preloader.texture[k][i] = v..l
end
end
end
end

ROBLOX - Why is this fly script working only in the Studio?

I really need help..
I have this code for fly, as a backpack item:
Name = "Fly"
pi = 3.141592653589793238462643383279502884197163993751
a = 0
s = 0
ndist = 13
rs = 0.025
siz = Vector3.new(1, 1, 1)
form = 0
flow = {}
function CFC(P1,P2)
local Place0 = CFrame.new(P1.CFrame.x,P1.CFrame.y,P1.CFrame.z)
local Place1 = P2.Position
P1.Size = Vector3.new(P1.Size.x,P1.Size.y,(Place0.p - Place1).magnitude)
P1.CFrame = CFrame.new((Place0.p + Place1)/2,Place0.p)
end
function checktable(table, parentneeded)
local i
local t = {}
for i = 1, #table do
if table[i] ~= nil then
if string.lower(type(table[i])) == "userdata" then
if parentneeded == true then
if table[i].Parent ~= nil then
t[#t + 1] = table[i]
end
else
t[#t + 1] = table[i]
end
end
end
end
return t
end
if script.Parent.Name ~= Name then
User = game:service("Players").Nineza
HB = Instance.new("HopperBin")
HB.Name = Name
HB.Parent = User.StarterGear
script.Parent = HB
User.Character:BreakJoints()
end
speed = 50
script.Parent.Selected:connect(function(mar)
s = 1
torso = script.Parent.Parent.Parent.Character.Torso
LeftShoulder = torso["Left Shoulder"]
RightShoulder = torso["Right Shoulder"]
LeftHip = torso["Left Hip"]
RightHip = torso["Right Hip"]
human = script.Parent.Parent.Parent.Character.Humanoid
bv = Instance.new("BodyVelocity")
bv.maxForce = Vector3.new(0,math.huge,0)
bv.velocity = Vector3.new(0,0,0)
bv.Parent = torso
bg = Instance.new("BodyGyro")
bg.maxTorque = Vector3.new(0,0,0)
bg.Parent = torso
connection = mar.Button1Down:connect(function()
a = 1
bv.maxForce = Vector3.new(math.huge,math.huge,math.huge)
bg.maxTorque = Vector3.new(900000,900000,900000)
bg.cframe = CFrame.new(torso.Position,mar.hit.p) * CFrame.fromEulerAnglesXYZ(math.rad(-90),0,0)
bv.velocity = CFrame.new(torso.Position,mar.hit.p).lookVector * speed
moveconnect = mar.Move:connect(function()
bg.maxTorque = Vector3.new(900000,900000,900000)
bg.cframe = CFrame.new(torso.Position,mar.hit.p) * CFrame.fromEulerAnglesXYZ(math.rad(-90),0,0)
bv.velocity = CFrame.new(torso.Position,mar.hit.p).lookVector * speed
end)
upconnect = mar.Button1Up:connect(function()
a = 0
moveconnect:disconnect()
upconnect:disconnect()
bv.velocity = Vector3.new(0,0,0)
bv.maxForce = Vector3.new(0,math.huge,0)
torso.Velocity = Vector3.new(0,0,0)
bg.cframe = CFrame.new(torso.Position,torso.Position + Vector3.new(torso.CFrame.lookVector.x,0,torso.CFrame.lookVector.z))
wait(1)
end)
end)
while s == 1 do
wait(0.02)
flow = checktable(flow, true)
local i
for i = 1,#flow do
flow[i].Transparency = flow[i].Transparency + rs
if flow[i].Transparency >= 1 then flow[i]:remove() end
end
if a == 1 then
flow[#flow + 1] = Instance.new("Part")
local p = flow[#flow]
p.formFactor = form
p.Size = siz
p.Anchored = true
p.CanCollide = false
p.TopSurface = 0
p.BottomSurface = 0
if #flow - 1 > 0 then
local pr = flow[#flow - 1]
p.Position = torso.Position - torso.Velocity/ndist
CFC(p, pr)
else
p.CFrame = CFrame.new(torso.Position - torso.Velocity/ndist, torso.CFrame.lookVector)
end
p.BrickColor = BrickColor.new("Cyan")
p.Transparency = 1
p.Parent = torso
local marm = Instance.new("BlockMesh")
marm.Scale = Vector3.new(1.9, 0.9, 1.725)
marm.Parent = p
local amplitude
local frequency
amplitude = pi
desiredAngle = amplitude
RightShoulder.MaxVelocity = 0.4
LeftShoulder.MaxVelocity = 0.4
RightHip.MaxVelocity = pi/10
LeftHip.MaxVelocity = pi/10
RightShoulder.DesiredAngle = desiredAngle
LeftShoulder.DesiredAngle = -desiredAngle
RightHip.DesiredAngle = 0
LeftHip.DesiredAngle = 0
end
end
end)
script.Parent.Deselected:connect(function()
a = 0
s = 0
bv:remove()
bg:remove()
if connection ~= nil then
connection:disconnect()
end
if moveconnect ~= nil then
moveconnect:disconnect()
end
if upconnect ~= nil then
upconnect:disconnect()
end
while s == 0 do
wait()
if #flow > 0 then
flow = checktable(flow, true)
local i
for i = 1,#flow do
flow[i].Transparency = flow[i].Transparency + rs
if flow[i].Transparency >= 1 then flow[i]:remove() end
end
end
end
end)
while true do
wait()
if s == 1 then
return
end
end
script:remove()
The script is in a HopperBin Object in the game's StarterPack Folder.
Now if you try it on your own, you'll see that it will work, BUT if you publish the game, play it via ROBLOX(not the studio) and try to use the item, you won't fly.
Any ideas why?
It's been a long time since I haven't played ROBLOX, so my answer might be inaccurate.
First, you need to understand the difference between a Script and a Localscript. In a nutshell, a script runs server-side whereas a Localscript runs client-side. Your fly script is expected to run on a player's client, thus you have to use a Localscript.
Your regular script works in build-mode because scripts are run on your client, and thus are considered as Localscripts. When you publish your game and play it, your computer doesn't work as a server anymore, but as a client.
In addition to this, as you use a localscript, you may have to change the following line :
-- gets the client (local player) on which the script is running
User = Game:GetService("Players").LocalPlayer
Also, avoid relative paths such as script.Parent.Parent.Parent..... You want to get the client's torso, so just use your User variable as per : User.Character.Torso. Do the same for the character's Humanoid object.
I think it's because the time to load not existing try this at line1:
repeat wait() until game.Players.LocalPlayer.Character

Corona SDK: Inserting into tables

I've read the other topics related to this subject and cannot make sense of them in the sense of my code. In the code below, I cannot get the make other word buttons into the table. I can generate the words but they will not go into the table. The previous function with the correct word works fine. What am I doing wrong? Do I have problems elsewhere in the code?
--main text
local content = require "content"
--chooses a random number according to the maximum number available in the table
local defaultWidth = 1024
local defaultHeight = 768
local displayWidth = display.viewableContentWidth
local displayHeight = display.viewableContentHeight
local yMargin = 20
local centerX = defaultWidth/2;
local centerY = defaultHeight/2;
local xAdjust = (defaultWidth - display.viewableContentWidth)/2
local yAdjust = (defaultHeight - display.viewableContentHeight)/2
local rnd = math.random
local maxSightwords = 3
local currQuestion = 0
local playOrder
local letterButtons
local wrongGraphic
local correctButton
--local wordButtons
function getRandomOrder(amount)
local order ={}
local i
local temp
local temp1
for n = 1,amount do
order[n] = n
end
for i=0,9 do
for temp = 1,amount do
n = math.random(1, amount)
temp1 = order[temp]
order[temp] = order[n]
order[n] = temp1
end
end
return order
end
-- assign random order for words
playOrder = getRandomOrder(#content)
function nextQuestion()
-- update question number index
currQuestion = currQuestion+1
if currQuestion > #playOrder then
currQuestion = 1
end
local questionNumber = playOrder[currQuestion]
print("Question# "..currQuestion)
print("id "..content[questionNumber].id)
-- make word buttons
wordButtons = {}
-- make word button for correct word
local word = content[playOrder[currQuestion]].word
table.insert(wordButtons, newWordButton(word))
correctButton = wordButtons[1].graphics
local buttonWidth = 150
print ("correct: "..word)
print (#wordButtons)
---[[
-- ****make other word buttons***
local otherWords = getRandomWords(content.word)
--print (otherWords)
for i=1, maxSightwords-1 do
table.insert(wordButtons, otherWords)
end
--]]
print (#wordButtons)
-- position letter buttons and add touch event listener
local randomWordOrder = getRandomOrder(#wordButtons)
local buttonSpacing = buttonWidth * 1.5
local buttonsWidth = (#wordButtons * buttonWidth) + ((#wordButtons-1) * (buttonSpacing/4))
local buttonsX = centerX - (buttonWidth)
for i=1, #wordButtons do
local button = wordButtons[i].graphics
button.y = centerY
button.x = buttonsX + (buttonSpacing * (randomWordOrder[i]-1))
button:addEventListener("touch", onWordTouch)
--local randomDelay = transitionDuration + (math.random(1,10) * 10)
--transition.from(button, {time = 500, delay = randomDelay, y = defaultHeight + button.height})
end
end
function clearQuestion()
-- remove wrongGraphic if present
if wrongGraphic then
wrongGraphic:removeSelf()
wrongGraphic = nil
end
-- remove all word buttons
for i=1,#wordButtons do
wordButtons[i].graphics:removeSelf()
wordButtons[i].graphics = nil
end
end
function onWordTouch(event)
local t = event.target
if "ended" == event.phase then
if t == correctButton then
onCorrect()
else
onIncorrect(t)
end
end
end
function onIncorrect(incorrectButton)
media.playSound("sounds/splat.wav")
wrongGraphic = display.newImageRect("images/graphics/wrong.png", 137, 136)
wrongGraphic.x = incorrectButton.x + incorrectButton.width/2
wrongGraphic.y = incorrectButton.y + incorrectButton.height/2
transition.to(incorrectButton, {time=100, delay=500, alpha=0})
transition.to(wrongGraphic, {time=200, delay=500, alpha=0, onComplete=wrongCompleteListener})
local wrongCompleteListener = function(obj)
obj:removeSelf()
obj = nil
incorrectButton:removeSelf()
incorrectButton = nil
end
end
function onCorrect()
-- play correct sound then display word
media.playSound("sounds/correct.mp3", playWord)
-- remove the letter buttons
clearQuestion()
-- disable the home button until new screen is shown
homeEnabled = false
end
function newWordButton(word)
local wordGraphic = display.newImageRect("images/words/"..word..".png", 150, 75)
local wordButton = {}
wordButton.graphics = display.newGroup()
wordButton.graphics:insert(wordGraphic)
wordButton.word = word
return wordButton
end
function getRandomWords ()
local wordGraphic = display.newGroup ()
for i=1,maxSightwords-1 do
--remove a word from content using a random index #
--Since the index will be between 1 and the number of words in content
--and each time through the loop a word is removed, you can be sure
--You will get 3 different words without repeats.
local next_word = table.remove(content, math.random(#content))
--next_word is a table with 'word' and 'id' fields so you can make the text display object from next_word.word
local wordText = display.newImageRect("images/words/"..next_word.id..".png", 150, 75)
wordText.x = display.contentWidth/2
wordText.y = display.contentHeight/2 - 100
wordGraphic:insert(wordText)
print (next_word.id)
end
end
nextQuestion ()
I think your problem is that you are resetting the wordButton = {} again in function newWordButton. You already made the table in function nextQuestion(), so by calling it again in the newWordButton function is reseting the entire table.
Take a look at this links:
http://www.coronalabs.com/blog/2011/06/21/understanding-lua-tables-in-corona-sdk/
http://docs.coronalabs.com/api/library/table/insert.html
I'm pretty sure the function should look like this:
function newWordButton(word)
local wordGraphic = display.newImageRect("images/words/"..word..".png", 150, 75)
wordButton.graphics = display.newGroup()
wordButton.graphics:insert(wordGraphic)
wordButton.word = word
return wordButton
end

how to get array value in lua in not using id

i have this array in my lua...
local data = {}
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"
data[3] = {}
data[3].title = "Bitter Child of Mine"
data[3].subtitle = "by Gunz n bullets"
data[3].image = "note.png"
data[4] = {}
data[4].title = "Missed A thing"
data[4].subtitle = "by Ero-Smith"
data[4].image = "note.png"
data[5] = {}
data[5].title = "Pornstar"
data[5].subtitle = "by Nicklefront"
data[5].image = "note.png"
data[6] = {}
data[6].title = "Burner"
data[6].subtitle = "by Asher"
data[6].image = "note.png"
how can i get the array values by not using id on it. i just want to get the title for my conditional statement?
i try this in my code:
local getTitle = function(event)
print (".................")
print (event.target.id)
print (event.target.title)
end
but i got only this...
touch: began
touch: ended
.................
2
nil
how can i get and print the title of my array?
this is my code:
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)
localGroup:insert(background)
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"
data[3] = {}
data[3].title = "Bitter Child of Mine"
data[3].subtitle = "by Gunz n bullets"
data[3].image = "note.png"
data[4] = {}
data[4].title = "Missed A thing"
data[4].subtitle = "by Ero-Smith"
data[4].image = "note.png"
data[5] = {}
data[5].title = "Pornstar"
data[5].subtitle = "by Nicklefront"
data[5].image = "note.png"
data[6] = {}
data[6].title = "Burner"
data[6].subtitle = "by Asher"
data[6].image = "note.png"
local topBoundary = display.screenOriginY + 40
local bottomBoundary = display.screenOriginY + 0
local getTitle = function(event)
print (".................")
print (event.target.id)
print (event.target.title)
end
songList = tableView.newList{
data=data,
default="listItemBg.png",
over="listItemBg_over.png",
onRelease=getTitle,
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
}
localGroup:insert(songList)
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)
localGroup:insert(navBar)
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
localGroup:insert(navHeader)
--backBtn.alpha = 0
local listBackground = display.newRect( 0, 0, songList.width, songList.height )
listBackground:setFillColor(255,255,255)
songList:insert(1,listBackground)
--Setup the back button
function changeScene(e)
if e.phase == 'ended' then
print ("ok")
director:changeScene(e.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", changeScene)
return localGroup
end
i got it...
i do this
local getTitle = function(event)
print (".................")
local id = event.target.id
print (id)
print (data[id].title)
end

Resources