is there a fix for Nil value for local user - lua

This is for a phone script ive been working on and im trying to update some code but I have been getting a single error.
Error #phone/server.lua:37: attempt to index a nil value (local 'user')
ref (#phone/server.lua:37)
handler (#framework/server/main.lua:242)
getNumberPhone (#phone/server.lua:36)
handler (#phone/server.lua:268)
I tried the one way I was shown here before with no luck.
line 37
function getNumberPhone(source, n)
local n = 0
TriggerEvent('f:getPlayer', source, function(user)
n = user.getPhoneNumber()
end)
return n
end
line 242
AddEventHandler("f:getPlayer", function(user, cb)
if not cb then return end
if(Users)then
if(Users[user])then
cb(Users[user])
else
cb(nil)
end
else
cb(nil)
end
end)
line 36
function getNumberPhone(source, n)
local n = 0
TriggerEvent('f:getPlayer', source, function(user)
n = user.getPhoneNumber()
end)
return n
end
line 286
RegisterServerEvent('gcPhone:allUpdate')
AddEventHandler('gcPhone:allUpdate', function()
local source = source
local identifier = GetPlayerIdentifiers(source)[1]
TriggerClientEvent("gcPhone:myPhoneNumber", source, getNumberPhone(source))
TriggerClientEvent("gcPhone:allMessage", source, getMessages(identifier,source))
TriggerClientEvent("gcPhone:contactList", source, getContacts(identifier))
end)

Explaining the Error
In Lua, this is one of the most common errors you will run into, so it is very important for you to know how to solve it.
The error: attempt to index a nil value
To understand what this error means, you only need to understand these concepts.
In Lua, only tables can be indexed (i.e. myTable[myIndex])
In Lua, if a variable evaluates to nil, then attempting to index it as if it were a table throws an error
So it should be a little easier to understand the error you received. A more explicit way to describe this error would be something like "the Lua interpreter attempted to index your variable user on line 37 but user evaluated to nil."
Your Specific Case
On line 242 you are calling a callback and passing nil
cb(nil)
This callback sends this nil value to line 37 as the user parameter
TriggerEvent('f:getPlayer', source, function(user)
n = user.getPhoneNumber()
end)
So when you try to run user.getPhoneNumber() you are actually running nil.getPhoneNumber(), which throws the error you saw.
Ways to fix this type of error
1) Whenever you are working with a variable that could be nil, create an if statement checking to see if it is nil before proceeding.
2) Make sure you never set that variable to nil.
Ways to fix your specific error
1) On line 36, create this if statement
TriggerEvent('f:getPlayer', source, function(user)
if user ~= nil then
n = user.getPhoneNumber()
end
end)
Or do a similar nil check like this
TriggerEvent('f:getPlayer', source, function(user)
if user then
n = user.getPhoneNumber()
end
end)
2) Always pass a user in your callback. For example, on line 242 and elsewhere, pass an actual user object.
cb(Users[someUser])

Related

Roblox studio error "Attempt to concatenate string with Instance"

So I got this error and I cant seem to fix it.
Can anyone tell me how to fix it?
The error was : Attempt to concatenate string with Instance.
Image of the full error
The function:
function chatfunc(msg) -- < error line 523
coroutine.wrap(function()
local amountsofchats = 0
for i,v in pairs(workspace:GetChildren()) do
if v.Name == "amogus"..plr then
amountsofchats += 1
end
end
if amountsofchats >= 5 then
return
end
for i,v in pairs(workspace:GetChildren()) do
if v.Name == "amogus"..plr then
v.StudsOffset += Vector3.new(0,2,0)
end
end
...
The second error thing:
game:GetService("Players")[Username].Chatted:Connect(function(msg)
local msg,Message_ = msg,msg
if string.sub(msg,1,3) == "/e " then
msg = string.sub(msg,4)
end
chatfunc(msg) -- < error line 717
end)
You are getting this error because are you trying to concat a string with an instance for example "string" .. Instance.new("Part").
Now since you didnt give any lines numbers with your code, I am assuming "amogus"..plr is what causes the error, since plr is here an instance you probably ment to do "amogus"..plr.Name which is concatting two strings
Also
i do not recommend doing this at all game:GetService("Players")[Username] if the user has name which is a property of Players service u will get the property instead of the player. for example if you have the username MaxPlayers that will return a number and not the player with that name thus your code will error. So I recommend doing game:GetService("Players"):FindFirstChild(Username)

attempt to index a nil value items(help!)

so im gettin this error so i know theres something i probably gotta fix here but i have no idea how .thanks
SCRIPT ERROR: #gcphone/server/server.lua:205: attempt to index a nil value (local 'items')
CODE FROM LINE 205
ESX.RegisterServerCallback('crew-phone:phone-check', function(source, cb)
local xPlayer = ESX.GetPlayerFromId(source)
if not xPlayer then return; end
for k, v in pairs(Config.Phones) do
local items = xPlayer.getInventoryItem(v)
if items.count > 0 then
cb(v)
return
end
end
cb(nil)
end)
ESX.RegisterServerCallback('crew-phone:item-check', function(source, cb, data)
local xPlayer = ESX.GetPlayerFromId(source)
if not xPlayer then return; end
local items = xPlayer.getInventoryItem(data)
cb(items.count)
end)
This error tells you that items is a nil value and Lua complains about it because you try to index it as in items.count. That doesn't make sense if items is nil
It's like referring to a book page of a non-existant book.
local items is nil because xPlayer.getInventoryItem(data) returned nil
Check wether the local script provides a string for data when triggering the server event and if xPlayer actually has an item like that.
Also check your RegisterServerCallback. The function you define there is the callback. Why is there another callback in that function argument? I think you're confusing things and probably should refer to the manual again.
https://esx-framework.github.io/es_extended/server/functions/registerservercallback/

Problem with script in lua, Error nil value (local 'xPlayer')

so when i try to buy something in shop it's just drop me this error.How to fix this?
Code:
RegisterServerEvent('esx_shops:buyItem')
AddEventHandler('esx_shops:buyItem', function(itemName, amount, zone)
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
local sourceItem = xPlayer.getInventoryItem(itemName)
amount = ESX.Round(amount)
-- is the player trying to exploit?
if amount < 0 then
print('esx_shops: ' .. xPlayer.identifier .. ' attempted to exploit the shop!')
return
end
Error:
SCRIPT ERROR: #esx_supermarket/server/main.lua:68: attempt to index a nil value (local 'xPlayer')
xPlayer is a nil value. nil values may not be indexed. Doing so causes an error.
So anything like xPlayer[something], xPlayer.something or xPlayer:something() is not allowed.
In your first example
local xPlayer = ESX.GetPlayerFromId(_source)
local sourceItem = xPlayer.getInventoryItem(itemName)
xPlayer is nil because ESX.GetPlayerFromId(_source) did not return a player. Most likely because _source is nil. At least there is nothing in your code that would indicate that source is not nil.
Befor you try to index possible nil values, check wether they are nil.
Please read the Lua manual and do a beginners tutorial.

Calling function from other file produces runtime error

I'm using Corona SDK for the first time and read up on how to call functions from other files, but I seem to be having issues. Here are the two scripts so far:
timer.lua
local M = {}
function M.Timer(n, count) --(period, how many times repeated)
if count > 0 then
local iter= os.time()+n
while iter ~= os.time() do
end
M.onTime(count)
count = count - 1
M.Timer(n,count)
end
end
function M.onTime(count)
display.newtext(count,250,50,native.systemFont,16)
end
return M
main.lua
local timeTool = require("timer")
timeTool.Timer(1,5)
They are located in the same directory. When I run main.lua on the simulator, I get the error attempt to call field 'Timer' (a nil value). This leads me to believe that the main file failed in acquiring the contents of the timer script, but from what I've seen, I am using the correct syntax. Is there something I missed, or am I using the wrong method for calling functions from other scripts?

Error in receiving data from server

I want to make my test function below print out the message "k isn't nil" but my code doesn't work. It has already received k value from my server but it doesn't check the line if k~=nil then. Below is my code. Thanks for any incoming advice.
local function receiveData( )
local l,e = client:receive()
if l~=nil then
print(l)
return l,e
else
timer.performWithDelay(100,receiveData)
end
end
function test( )
k = receiveData()
if k ~=nil then
print("k isn't nil")
end
end
test()
The problem is that if the data is not received on the first try then k is nil and test returns. The receiveData will be called again at 100 millisecond intervals until data is received, but the return is discarded by performWithDelay and by then test has returned (see first sentence of this answer).
The solution is to set a callback that receiveData can call when the data eventually arrives. The callback can then process the data. Replace return l,e by onReceiveData(l,e) and have that do something that test waits for in a while loop. Of course receiveData could directly set this flag being watched by test but once your app gets larger it is a good idea to separate receive from process.
function receiveData()
...
-- then:
local data = nil
function onReceiveData(l,e)
data = l
print('ready to process data', data, e)
end
funtion test()
receiveData()
while data == nil do sleep(100) end
print('data received and processed')
end
test()
where sleep(100) is what you can come up with since there is no builtin function that does that in Lua or even Corona (although Corona has system.getTimer() which returns ms since app start, so you could have
function sleep(ms)
local start = system.getTimer()
while system.getTimer() - start < ms do
end
end
I'm not too keen on the empty while loop but in a test utility function it is OK. If you are using the socket library it has a sleep function -- check out the Lua wiki for other options).
Are you sure you received the data? What does your program print in the console?
You may consider the following modification
local function receiveData( )
local l,e = client:receive()
if l~=nil then
print(l)
return l,e
else
timer.performWithDelay(100,function() l, e = receiveData() end)
end
return l, e
end
So my guess is, that when receiveData gets called second time, your return values (l, e) are discarded (because performWithDelay doesn't do anything with them).

Resources