LUA unexpected symbol near ')' - lua

fivem
local loaded = false
function loadTxd(source, args, raw)
local txd = CreateRuntimeTxd('duiTxd')
local duiObj = CreateDui('https://media.discordapp.net/attachments/813996951066116097/854844624114548786/lcd_sign1.gif', 4096, 1024)
_G.duiObj = duiObj
local dui = GetDuiHandle(duiObj)
local tx = CreateRuntimeTextureFromDuiHandle(txd, 'duiTex', dui)
AddReplaceTexture('bus', 'lcd_sign_1', 'duiTxd', 'duiTex')
end)
Citizen.CreateThread function loadTxd(source, args, raw)
while loaded == false do
Wait(0)
local playerCar = GetVehiclePedIsIn(GetPlayerPed(-1))
if playerCar ~= 0 then
if GetEntityModel(playerCar) == GetHashKey('bus') then
loadTxd()
loaded = true
end
end
if not loaded then
local veh = nil
for veh in EnumerateVehicles() do
if GetEntityModel(playerCar) == GetHashKey('bus') then
loadTxd()
loaded = true
break
end
end
end
end
end)
says it lua5.3: ...Desktop/rextester_linux_2.0/usercode/29524824/source.lua:10: unexpected symbol near ')' but I can't find it anywhere I even tried deleting the whole line 10 and pasting all the code back in and then putting the end) on line 10

There are a few syntax errors here:
The extra ) after end on line 10, which is the error you're seeing
An opening parenthesis is missing after Citizen.CreateThread
When you write function foo(...), that's equivalent to writing foo = function(...). You can't give a function a name when you're using it inline, like you are with the one you're passing to Citizen.CreateThread.
So, to fix the syntax errors, the middle part of your code (lines 10–12) should read:
...
end
Citizen.CreateThread(function(source, args, raw)
...

Related

LUA - ZeroBrane IDE: Compile feature

in ZeroBrane Studio if I use "Project - complile (F7)" - what exactly does happen?
Will there be a standalone .exe created from my Lua code ?
And if so - in which directory ?
I use Windows 10.
(Couldn't find any information in the documention)
From what I see by a quick look into the source code it simply checks whether the code has any errors by loading it using loadstring which compiles the file.
There is no output file, just some text output about any errors.
But that's just an assumption. Feel free to check if this is actually the function called when you click that button.
https://github.com/pkulchenko/ZeroBraneStudio/blob/5daf55d79449431ca9794f6b8a65476dc203b780/src/editor
function CompileProgram(editor, params)
local params = {
jumponerror = (params or {}).jumponerror ~= false,
reportstats = (params or {}).reportstats ~= false,
keepoutput = (params or {}).keepoutput,
}
local doc = ide:GetDocument(editor)
local filePath = doc:GetFilePath() or doc:GetFileName()
local loadstring = loadstring or load
local func, err = loadstring(StripShebang(editor:GetTextDyn()), '#'..filePath)
local line = not func and tonumber(err:match(":(%d+)%s*:")) or nil
if not params.keepoutput then ClearOutput() end
compileTotal = compileTotal + 1
if func then
compileOk = compileOk + 1
if params.reportstats then
ide:Print(TR("Compilation successful; %.0f%% success rate (%d/%d).")
:format(compileOk/compileTotal*100, compileOk, compileTotal))
end
else
ide:GetOutput():Activate()
ide:Print(TR("Compilation error").." "..TR("on line %d"):format(line)..":")
ide:Print((err:gsub("\n$", "")))
-- check for escapes invalid in LuaJIT/Lua 5.2 that are allowed in Lua 5.1
if err:find('invalid escape sequence') then
local s = editor:GetLineDyn(line-1)
local cleaned = s
:gsub('\\[abfnrtv\\"\']', ' ')
:gsub('(\\x[0-9a-fA-F][0-9a-fA-F])', function(s) return string.rep(' ', #s) end)
:gsub('(\\%d%d?%d?)', function(s) return string.rep(' ', #s) end)
:gsub('(\\z%s*)', function(s) return string.rep(' ', #s) end)
local invalid = cleaned:find("\\")
if invalid then
ide:Print(TR("Consider removing backslash from escape sequence '%s'.")
:format(s:sub(invalid,invalid+1)))
end
end
if line and params.jumponerror and line-1 ~= editor:GetCurrentLine() then
editor:GotoLine(line-1)
end
end
return func ~= nil -- return true if it compiled ok
end

Garry's mod lua code error not working (Entity X, got nil)

I tried to fix some Garry's Mod addon and this is what happens. I tried to fix it for long time, but I'm not the best in Lua coding :/ . What is wrong with this code? I get this error:
[ERROR] addons/garrys_bombs_5_base_528449144/lua/entities/gb5_shockwave_sound_lowsh.lua:80: bad argument #1 to 'SetPhysicsAttacker' (Entity expected, got nil)
1. SetPhysicsAttacker - [C]:-1
2. unknown - addons/garrys_bombs_5_base_528449144/lua/entities/gb5_shockwave_sound_lowsh.lua:80
And the code is pretty long. I have every file working fine, but this file is not working
AddCSLuaFile()
DEFINE_BASECLASS( "base_anim" )
if (SERVER) then
util.AddNetworkString( "gb5_net_sound_lowsh" )
end
ENT.Spawnable = false
ENT.AdminSpawnable = false
ENT.PrintName = ""
ENT.Author = ""
ENT.Contact = ""
ENT.GBOWNER = nil
ENT.MAX_RANGE = 0
ENT.SHOCKWAVE_INCREMENT = 0
ENT.DELAY = 0
ENT.SOUND = ""
net.Receive( "gb5_net_sound_lowsh", function( len, pl )
local sound = net.ReadString()
LocalPlayer():EmitSound(sound)
end );
function ENT:Initialize()
if (SERVER) then
self.FILTER = {}
self:SetModel("models/props_junk/watermelon01_chunk02c.mdl")
self:SetSolid( SOLID_NONE )
self:SetMoveType( MOVETYPE_NONE )
self:SetUseType( ONOFF_USE )
self.Bursts = 0
self.CURRENTRANGE = 0
self.GBOWNER = self:GetVar("GBOWNER")
self.SOUND = self:GetVar("SOUND")
end
end
function ENT:Think()
if (SERVER) then
if not self:IsValid() then return end
local pos = self:GetPos()
self.CURRENTRANGE = self.CURRENTRANGE+(self.SHOCKWAVE_INCREMENT*10)
if(GetConVar("gb5_realistic_sound"):GetInt() >= 1) then
for k, v in pairs(ents.FindInSphere(pos,self.CURRENTRANGE)) do
if v:IsPlayer() then
if not (table.HasValue(self.FILTER,v)) then
net.Start("gb5_net_sound_lowsh")
net.WriteString(self.SOUND)
net.Send(v)
v:SetNWString("sound", self.SOUND)
if self:GetVar("Shocktime") == nil then
self.shocktime = 1
else
self.shocktime = self:GetVar("Shocktime")
end
if GetConVar("gb5_sound_shake"):GetInt()== 1 then
util.ScreenShake( v:GetPos(), 5555, 555, self.shocktime, 500 )
end
table.insert(self.FILTER, v)
end
end
end
else
if self:GetVar("Shocktime") == nil then
self.shocktime = 1
else
self.shocktime = self:GetVar("Shocktime")
end
local ent = ents.Create("gb5_shockwave_sound_instant")
ent:SetPos( pos )
ent:Spawn()
ent:Activate()
ent:SetPhysicsAttacker(ply)
ent:SetVar("GBOWNER", self.GBOWNER)
ent:SetVar("MAX_RANGE",50000)
ent:SetVar("DELAY",0.01)
ent:SetVar("Shocktime",self.shocktime)
ent:SetVar("SOUND", self:GetVar("SOUND"))
self:Remove()
end
self.Bursts = self.Bursts + 1
if (self.CURRENTRANGE >= self.MAX_RANGE) then
self:Remove()
end
self:NextThink(CurTime() + (self.DELAY*10))
return true
end
end
function ENT:OnRemove()
if SERVER then
if self.FILTER==nil then return end
for k, v in pairs(self.FILTER) do
if not v:IsValid() then return end
v:SetNWBool("waiting", true)
end
end
end
function ENT:Draw()
return false
end
Is there a chance someone fix this for me? Or even just telling me what's wrong? I would be pleased. If needed I can send all files. Well... It's not my addon but I'm trying to fix an existing one. Someone tried to fix it too but he didn't (actually he broke it even more).
What the error means
Inside your ENT:Think() function, you are calling ent:SetPhysicsAttacker(ply)
ply is not defined anywhere inside that function, so is nil (Entity expected, got nil)
How to fix this
If no player is responsible for the damage caused by this entity, delete the line ent:SetPhysicsAttacker(ply).
Otherwise, assign an Owner to the entity at the point of creation, using SetOwner.
This would then allow you to use self:GetOwner() inside your Think hook
Example
hook.Add("PlayerSay", "SpawnEntity", function(ply, text)
if string.lower(text) == "!spawnentity" then
-- Create your entity
local myEntity = ents.Create("gb5_shockwave_sound_lowsh")
myEntity:SetPos(ply:GetPos())
myEntity:SetAngles(ply:GetAngles())
myEntity:Spawn()
-- Sets the owner to the player that typed the command
myEntity:SetOwner(ply)
return ""
end
end)
-- Inside your entity code
function ENT:Think()
print("My owner is: " .. tostring(self:GetOwner()))
-- ...
ent:SetPhysicsAttacker(self:GetOwner())
end

.lua error 'then' expected near 'else'

I am having this error, can't find the error.
local choice_revive = {function(player,choice)
local user_id = vRP.getUserId(player)
if user_id ~= nil then
vRPclient.getNearestPlayer(player,{10},function(nplayer)
local nuser_id = vRP.getUserId(nplayer)
if nuser_id ~= nil then
vRPclient.isInComa(nplayer,{}, function(in_coma)
if in_coma then
if vRP.tryGetInventoryItem(user_id,"medkit",1,true) else
vRP.tryGetInventoryItem(user_id,"smartwatch",1,true)
io.write("Smartwatch: Tilkalder Ambulance")
then
vRPclient.playAnim(player,{false,revive_seq,false}) -- anim
SetTimeout(15000, function()
vRPclient.varyHealth(nplayer,{50}) -- heal 50
end)
end
else
vRPclient.notify(player,{lang.emergency.menu.revive.not_in_coma()})
end
end)
else
vRPclient.notify(player,{lang.common.no_player_near()})
end
end)
end
end,lang.emergency.menu.revive.description()}
I have tried to make, and look for error, but without luck.
- If anyone can fix it, tell me please.
if statement, functions and for statement must be ended with end.
this code must be like that
--Settings--
local Tunnel = module("vrp", "lib/Tunnel")
local Proxy = module("vrp", "lib/Proxy")
vRP = Proxy.getInterface("vRP")
vRPclient = Tunnel.getInterface("vRP","vRP_smartwatch")
if in_coma then
vRP.tryGetInventoryItem(user_id,"smartwatch",1,true)
io.write("Smartwatch: Tilkalder Ambulance")
end
function vRP.sendServiceAlert(sender, emergency,x,y,z, msg)
local service = services[service_name]
local answered = false
if service then
local players = {}
for k,v in pairs(vRP.rusers) do
local player = vRP.getUserSource(tonumber(k))
-- check user
if vRP.hasPermission(k,service.alert_permission) and player ~= nil then
table.insert(players,player)
end
end
end
end

Lua/Corona EOF Error

(This continues from my first question.)
This is an EOF End of File error in which it says that an EOF was expected near my line 19, which you can see in the code below.
display.setStatusBar(display.HiddenStatusBar)
local director = {scene = 'main'}
function director:changeScene (moduleName)
if type(moduleName) == 'nil' or self.scene == moduleName then return end
local loadedModule = package.loaded[self.scene]
if type(loadedModule) == 'table' and type(loadedModule.clean) == 'function' then
loadedModule.clean()
end
if self.view then self.view:removeSelf() end
if self.scene ~= 'main' and type(loadedModule) == 'table' then
package.loaded[self.scene], self.view, loadedModule = nil
collectgarbage('collect')
end
self.view, self.scene = require(moduleName).new(), moduleName
end
return director
local mainGroup = display.newGroup() -- This is line 19
maingroup:insert(director.directorView)
director:changeScene("mainPage.lua")
return mainGroup
(If you didn't know, the director stuff is a way to manually access the file, that's not the problem in the code.)
The error is:
Line: 19
'' expected near 'local'
And line 19 is: local mainGroup = display.newGroup()
See my earlier question for a little background on the problem.
After a return there can be no further statements: a return must be the last statement in a block.
But it seems to me that you forgot an end after that return.

Is This A lua Variable Scope Issue (and how can it be solved)?

A very strange error, showing an object is nil.
the code in subject is
while pbs:HasNext() do
local char = self.DecodeCharacter(pbs)
...
One would think, that if pbs:HasNext() is true, it means that, pbs is not nil, whatsoever.
However, the print(pbs) - the first line of HTMLEntityCodec:DecodeCharacter prints nil
function HTMLEntityCodec:DecodeCharacter(pbs)
print(pbs)
...
The entire file dumped below, it was stripped from 1800+ lines to 110 so it can be clear for SO users to get he context. But that stripping took away all logic from the code, so do not get confused by that.
#!/usr/bin/env lua
function Inherits( baseClass )
local new_class = {}
local class_mt = { __index = new_class }
function new_class:create()
local newinst = {}
setmetatable( newinst, class_mt )
return newinst
end
if baseClass then
setmetatable( new_class, { __index = baseClass } )
end
return new_class
end
-------------------------------------------
-- PushbackString
-------------------------------------------
PushbackString = Inherits({})
function PushbackString:Init(input)
self.input = input
self.pushback = nil
self.temp = nil
self.index = 0
self.mark = 0
end
-- Mark the current index, so the client can reset() to it if need be.
function PushbackString:HasNext()
return true
end
function PushbackString:Mark ()
self.temp = self.pushback
self.mark = self.index
end
BaseCodec = Inherits({})
function BaseCodec:Decode(input)
local buff = ''
local pbs = PushbackString:create()
pbs:Init(input)
while pbs:HasNext() do
local char = self.DecodeCharacter(pbs)
if char ~= nil then
buff = buff .. char
else
buff = buff .. pbs:Next()
end
end
return buff
end
HTMLEntityCodec = Inherits(BaseCodec)
-- HTMLEntityCodec.classname = ('HTMLEntityCodec')
function HTMLEntityCodec:DecodeCharacter(pbs)
print(pbs)
pbs:Mark()
end
DefaultEncoder = Inherits({})
function DefaultEncoder:Init(codecs)
self.html_codec = HTMLEntityCodec:create()
end
function DefaultEncoder:TestInput(input , strict)
print ("\n----------------8<----------------8<----------------\n")
print ("Input:\t" .. input)
-- default value
if strict == nil then strict = true end
-- nothing to do
if input == nil then return nil end
local working = input
local codecs_found = {}
local found_count = 0
local clean = false
while not clean do
clean = true
old = working
working = self.html_codec:Decode( working )
if old ~= working then
print ("Warning:\tINTRUSION DETECTED")
end
end
print ("Output:\t".. working)
return working
end
local default_encoder = DefaultEncoder:create()
default_encoder:Init()
default_encoder:TestInput("%25", true)
----------8<-----------8<--------------8<----------------
END OF FILE
Console Output:
tzury#1005:~/devel/lua$ lua problem.lua
----------------8<----------------8<----------------
Input: %25
nil
lua: problem.lua:70: attempt to index local 'pbs' (a nil value)
stack traceback:
problem.lua:70: in function 'DecodeCharacter'
problem.lua:54: in function 'Decode'
problem.lua:96: in function 'TestInput'
problem.lua:109: in main chunk
[C]: ?
In your code, the crash happens on this line:
local char = self.DecodeCharacter(pbs)
The problem is that you are calling DecodeCharacter with incorrect number of arguments.
Solution: call it like this (notice the colon):
local char = self:DecodeCharacter(pbs)
Explanation:
When you define functions in Lua using the colon (:), you are using a syntax sugar which hides an implicit first argument named self. Definitions like:
function HTMLEntityCodec:DecodeCharacter(pbs) ... end
Are actually 'translated' to this:
HTMLEntityCodec.DecodeCharacter = function (self, pbs) ... end
When you call the function, you either need to pass the self argument yourself, or use the colon call to supply it automatically. In your code (self.DecodeCharacter(pbs)), you are passing pbs which ends up as self in HTMLEntityCodec.DecodeCharacter, and pbs ends up being nil. Both following calls are equivalent and should solve the issue:
local char = self.DecodeCharacter(self, pbs)
local char = self:DecodeCharacter(pbs)

Resources