LUA ERROR running the app on android - lua

I'm a new programmer with no much experience; as a good noob it's very probable that the next code lines you will see may show a wide number of errors or imprecisions thus I'm excusing myself ahead of time.
So, the situation is the following:
Lately I'm interfacing with a new programming language (new for me obviously) that is LUA (using corona sdk). I approached the language writing simple codes.
Now I'm trying to execute a program that has simply to display two rectangles affected by the gravity. When I try to emulate the applicarion on my PC with CORONA it works without any kind of problem; after having built it for android OS, having installed it on my phone and having run it the result is an error message that is the following:
This is the error message:
"main.lua.35: ERROR: table expected. If this is a function call you might have used '.' instead of ':' "
This is the code:
local physics = require("physics")
physics.start()
local _W = display.contentWidth
local _H = display.contentHeight
local platform = display.newRect(
--x =
_W/2,
--y =
_H/2,
--width =
100,
--height =
100
)
platform.surfaceType = "rectangle"
local myImage = display.newImage("icon.png",_W/2,50)
local iconCollision = {
friction = 0.0, --attrito
bounce = 0.0, --rimbalzo (forse)
isSensor = true --collisione con altri oggetti
}
physics.addBody(platform,"static")
physics.addBody(myImage,"dynamic",iconCollision) --this is line 35
platform.collision = onCollision
local function onGyroscopeDataReceived( event )
local deltaRadians = event.zRotation * event.deltaTime
local deltaDegrees = deltaRadians * (180/math.pi)
end
local function dragImage(event)
local t=event.target
print(event.phase)
if(event.phase == "moved") then
t.x = event.x
t.y = event.y
end
end
local function onCollision( event )
if ( event.phase == "began" ) then
print("toccato")
end
end
if system.hasEventSource( "gyroscope" ) then
Runtime:addEventListener( "gyroscope", onGyroscopeDataReceived )
end
Runtime:addEventListener("collision",onCollision)
myImage:addEventListener("touch",dragImage)
I will be very grateful with those who will try to help me.

I think maybe event.zRotation is null. On iOS, you can use the appropriate UIRequiredDeviceCapabilities. In building.settings add this UIRequiredDeviceCapabilities = { ["gyroscope"]=true }. On Android set the usesFeatures = { { name="android.hardware.sensor.gyroscope", required=true } }.

Look for the name of the image on the disk , "icon.png", uppercase and lowercase matters, on Android device it could lead to errors, not showed in simulators.
If it doesn't load myImage:addEventListener would display an errore, maybe the one you see.
Also try to exclude pieces of code and then run the program on device back. I found difference with simulator that way.

Related

Rotating a Axe Model in Roblox

So, For Context im trying to emulate kind of like throwing an axe, when you throw an axe it spins and spins and spins vertically.However, I got the spinning part right but the axis that is at, is not right the axe it should be facing vertically not facing you, i will post a gyazo link just so u can see how it spins right now. https://gyazo.com/99eaa8c1b5b3ce22205148509e115b14
Ive tried a couple things, ive tweend it, i thought that would work, as tweening it i can do it infinitley, But the result was it being still. I also tried pivoting it, But because of my courtine. Sometimes it wouldnt even go through
Heres The roblox code
local function ZodiacMove(plr,Mouse)
local TestingCourotine = coroutine.create(function(Handle)
while true do RunService.Stepped:Wait()
print(Handle)
Handle.CFrame = Handle.CFrame * CFrame.Angles(0,0,math.rad(10))
if Handle.Parent == nil then break end
end
print('the axe has vanished :sob:')
end)
local ZodiacProjectile = game:GetService("ReplicatedStorage").Axe:Clone()
local Handle = ZodiacProjectile:FindFirstChild("Blade")["Blade Tip"]
print(Handle)
local ZodiacProjectilePivot = ZodiacProjectile:GetPivot()
ZodiacProjectile:PivotTo(ZodiacProjectilePivot * CFrame.new(math.rad(10),0,0))
coroutine.resume(TestingCourotine,Handle)
---TweenInfoGoals.CFrame = Handle.CFrame * CFrame.Angles(0,0,math.rad(360))
--local ZodiacProjectileTween = TweenService:Create(Handle, tweenInfo,TweenInfoGoals)
--ZodiacProjectileTween:Play()
local OverParams = OverlapParams.new()
OverParams.FilterType = Enum.RaycastFilterType.Blacklist
OverParams.FilterDescendantsInstances = {workspace.Baseplate, plr.Character, plr.Character:GetChildren()}
local HumanoidRootPart = plr.Character:WaitForChild("HumanoidRootPart")
local BV = Instance.new("BodyVelocity")
BV.Parent = Handle
ZodiacProjectile.Parent = HumanoidRootPart
BV.Velocity = HumanoidRootPart.CFrame.LookVector * 100
BV.MaxForce = Vector3.new(math.huge, math.huge, math.huge)
ZodiacProjectile:PivotTo( HumanoidRootPart.CFrame * CFrame.new(0, 0, -1))
Debris:AddItem(ZodiacProjectile,2)
end```

Roblox Item is lagging

I add a mesh to follow the player where ever he goes. But the mesh is lagging a bit when the player runs. I understand that it is not rendering quickly enough, but anyone know how to add a mesh without it lagging?
local humanoidRootPart = character:WaitForChild('HumanoidRootPart')
local backpackItemWorkspace = game.ReplicatedStorage.Meshes[pet.Name]:Clone()
backpackItemWorkspace.Parent = game.Workspace.CurrentPets
RunService.Stepped:Connect(function()
local location = humanoidRootPart.CFrame
backpackItemWorkspace.CFrame = location * CFrame.new(2, 2, 3)
end)
Connect the mesh and rootpart using a weld, so you dont need to use RunService to move the mesh everytime.
local humanoidRootPart = character:WaitForChild('HumanoidRootPart')
local backpackItemWorkspace = game.ReplicatedStorage.Meshes[pet.Name]:Clone()
backpackItemWorkspace.Parent = game.Workspace.CurrentPets
function attach(hroot, mesh)
local weld = Instance.new("WeldConstraint", mesh)
local location = hroot.CFrame
mesh.CFrame = location + Vector3.new(2, 2, 3)
weld.Part0 = hroot
weld.Part1 = mesh
return weld
end
attach(humanoidRootPart, backpackItemWorkspace)
-- please comment if it makes any errors
Ok, for others struggling with having a pet(mesh) follow you smoothly and always stay on your back. I have now spent several hours on this subject and finally got it to work. This is how you do it:
local character = player.Character
local humanoidRootPart = character:WaitForChild('HumanoidRootPart')
//where you copy you pet from
local backpackItemWorkspace = game.ReplicatedStorage.Meshes[pet.Name]:Clone()
//where you keep your pets in the workspace
backpackItemWorkspace.Parent = game.Workspace.CurrentPets
//call the function for attaching the pet
attachPet(backpackItemWorkspace, character, humanoidRootPart)
function attachPet (pet, char, humanoidRootPart)
local focusPart = humanoidRootPart
local newPet = pet
local z = -5
local x = 1
local bodyPos = Instance.new("BodyPosition")
bodyPos.Parent = newPet
bodyPos.MaxForce = Vector3.new(math.huge, math.huge, math.huge)
local bodyGyro = Instance.new("BodyGyro")
bodyGyro.Parent = newPet
bodyGyro.MaxTorque = Vector3.new(math.huge, math.huge, math.huge)
while wait() do
bodyPos.Position = focusPart.Position + focusPart.CFrame.LookVector * z + focusPart.CFrame.RightVector * x
bodyGyro.CFrame = focusPart.CFrame
end
end
Also when you unequip a pet you have to Destroy it from where you store it. In my case I store them in a folder on the player which I call collectionInventory.
local collectionInventory = player:WaitForChild("CollectionInventory")
collectionInventory[petName]:Destroy()
Hope this save anybody else from wasting several hours with research. Even though you will probably learn a lot from those "wasted hours" ;)

display.remove(obj) doesn't work, why ? (lua)

In this program when you tap on the object moon the function changeScene() should change scene from end.lua to start.lua (in order to restart the game).
But in the start.lua the moon remains on the display.
Therefore in changeScene() I add display.remove( moon ) but it does not work.
I tried moon:removeSelf() and sceneGroup:remove(3) too.
Furthermore I do not know why moon:removeSelf() gives this error:
ERROR: Runtime error
end.lua:13: attempt to index global 'moon' (a nil value)
stack traceback:
end.lua:13: in function '?'
?: in function <?:190>
What am I doing wrong?
end.lua
local composer = require( "composer" )
local scene = composer.newScene()
-- create()
function scene:create( event )
local sceneGroup = self.view
local function changeScene()
--moon:removeSelf()
--sceneGroup:remove(3)
display.remove( moon )
--moon = nil
composer.removeScene("end")
composer.gotoScene( "start", {effect = "slideUp", time = 500} )
end
local text = display.newText(correctAnswers .. "/10 correct ", display.contentCenterX, 280 ,native.systemFont, 50)
text.y = display.contentCenterY-100
sceneGroup:insert(text)
local text2 = display.newText("Press the moon to RESTART ", display.contentCenterX, 280 ,native.systemFont, 20)
text2.x = display.contentCenterX
text2.y = display.contentCenterY+200
transition.blink( text2, { time=2500 } )
sceneGroup:insert(text2)
local floor = display.newImageRect( "floor.png", 300, 50 )
floor.x = display.contentCenterX
floor.y = display.viewableContentHeight+100
local moon = display.newImageRect( "balloon.png", 112, 112 )
moon.x = math.random( 40,display.contentWidth-40 )
moon.y = 50
moon.alpha = 0.8
local physics = require( "physics" )
physics.start()
physics.addBody( floor, "static" )
physics.addBody( moon, "dynamic", { radius=50, bounce=0.5 } )
moon:addEventListener( "tap", changeScene )
end
It is fine to use local variables inside of functions. But variables can only be used when they are in scope.
Of course, variables that are in the parameter list of a function definition are in scope inside of the function. But variables which are not in the parameter list may also be used, provided that they are in scope at the time of function definition. In OP code, the changeScene function has no parameters, so any variables used in the function must be in scope at the time of function definition. The variable moon is a local variable, which is in scope in the block in which it is declared, after the point of definition. So, moon is not in scope when changeScene is defined. One way to fix this problem is to move the definition of moon to a point before the definition of changeScene:
local moon = display.newImageRect("balloon.png", 112, 112)
moon.x = math.random(40,display.contentWidth - 40)
moon.y = 50
moon.alpha = 0.8
local function changeScene ()
display.remove(moon)
composer.removeScene("end")
composer.gotoScene("start", {effect = "slideUp", time = 500})
end
in Lua, when we work with a function, whenever we are going to call a variable inside it, it must be local, but when we are inside a function calling a variable outside it, it must be global.
Remove the local in the moon variable declaration and see if that solves the problem
When using functions its fine to use a defined variable inside but you need to make sure 1 its local and 2 if its outside its global
try taking the local out of the defined moon variable and you might be able to fix it
:D

Loading modules from folders

My project structure is following:
--Shooter
----sprites
------background.png
------player.png
------zombie.png
----units
------player.lua
------zombie.lua
----main.lua
----load.lua
----update.lua
----draw.lua
And my main.lua will have the following:
local Bullet = require("units.bullet")
local Player = require("units.player")
local Zombie = require("units.zombie")
require("load")
require("update")
require("draw")
require("functions")
love.window.setTitle("Shooter")
function love.load()
Load()
end
function love.update(dt)
Update(dt)
end
function love.draw()
Draw()
end
For example, bullet.lua:
local Bullet = {}
bulletSprite = love.graphics.newImage('sprites/bullet.png')
function Bullet.create()
local newBullet = {
pos = {},
speed = 10,
sprite = bulletSprite,
direction = 0,
dead = false
}
return setmetatable(newBullet, {__index = Bullet})
end
function Bullet:setPos(x, y)
self.pos.x = x
self.pos.y = y
end
function Bullet:setDirection(angle)
self.direction = angle
end
function Bullet:move(dt)
local distance = self.speed * dt * 60
self.pos.x = self.pos.x + math.cos(self.direction) * distance
self.pos.y = self.pos.y + math.sin(self.direction) * distance
end
function spawnBullet(bullets, player)
local newBullet = Bullet.create()
newBullet:setPos(player.pos.x, player.pos.y)
newBullet.direction = player.angle
table.insert(bullets, newBullet)
end
The problem is that none of the files in units folder will load properly. From the error log I can see that it tries to search for bullet.lua in the root directory and then various love2d and lua libraries.
I have tried various things like require("./units/bullet") or replace / with . but so far, no luck.
Extracting those files from the units folder into root folder will work. Loading images from sprites folder works, however (for example love.graphics.draw(sprites.background, 0, 0)).
Any help?
I found out the problem was that while my main.lua had correct requires, my update file didn't.
Two things come to mind.
Make Sure LUA_PATH is set to your project directory
add return Bullet, return Player and so on... into each module you have created

Corona SDK(LUA) - attempt to call upvalue 'spawnEnemy'(a nil value)

I just trying to add eventListener to a object, which should disappear when I tap on it. But I get error mentioned in the title. Here is my whole code at this point :
-- housekeeping stuff
display.setStatusBar(display.HiddenStatusBar)
local centerX = display.contentCenterX
local centerY = display.contentCenterY
-- set up forward references
local spawnEnemy
-- preload audio
-- create play screens
local function createPlayScreen()
local bg = display.newImage("background.png")
bg.y = 130
bg.x = 100
bg.alpha = 0
local planet = display.newImage("planet.png")
planet.x = centerX
planet.y = display.contentHeight +60
planet.alpha = 0
transition.to( bg, { time = 2000, alpha = 1, y = centerY, x = centerX } )
local function showTitle()
local gametitle = display.newImage("gametitle.png")
gametitle.alpha = 0
gametitle:scale (4, 4)
transition.to( gametitle, { time = 500, alpha = 1, xScale = 1, yScale = 1 })
spawnEnemy()
end
transition.to( planet, { time = 2000, alpha = 1, y = centerY, onComplete = showTitle } )
end
-- game functions
local function shipSmash(event)
local obj = event.target
display.remove( obj )
end
local function spawnEnemy()
local enemy = display.newImage("beetleship.png")
enemy.x = math.random(20, display.contentWidth - 20)
enemy.y = math.random(20, display.contentHeight - 20)
enemy:addEventListener ( "tap", shipSmash )
end
local function startGame()
end
local function planetDamage()
end
local function hitPlanet(obj)
end
createPlayScreen()
startGame()
And here is how error window looks like :
I'm kinda new in this area(LUA programming) so sorry for maybe dumb syntax error or something, but what I saw is that this error shows up after I write this line of code: enemy:addEventListener ( "tap", shipSmash )
Change local function spawnEnemy() to function spawnEnemy() as this variable was already declared earlier. Yes, this is typical Lua pitfall for beginners.
You've declared spawnEnemy as a local variable twice. That's allowed (the second one hides the first where ever the second one is in scope) but that's not what you wanted.
You have correctly declared a local variable and captured it in showTitle. To set that very same variable later, use an assignment statement without prefixing it with local. You can assign it a function definition using the "anonymous" function syntax:
spawnEnemy = function()
...
end
Actually, in Lua, all functions are anonymous since they are just values. But, for debugging, it is helpful to have a name associated with a function. In stack traces, the name of the variable used to call the function is used, where possible.

Resources