When should I use pcall function in lua? Should I use it for all nk functions or just for sql_exec and sql_query functions?
pcall is a Lua function used to trap errors.
You can use it to trap errors in function calls that you make - either your own, other libraries, or those which come from the
nakama module you import. A good example is if you want to trap errors when a leaderboard is created:
local id = nk.uuid_v4() if pcall(nk.leaderboard_create, id, "desc", "best", "0 0 * * 1", json, false) then nk.logger_error("failed to create leaderboard") -- return an error? else nk.logger_info(("new leaderboard created: %q"):format(id)) end
You can have a look at our docs or the Lua manual for more examples:
I got sometimes some errors in sql_exec and sql_query but I did not get any errors in other nakama functions.Is there any problem if I use pcall just for those two functions?
@nkadd No problem. The SQL exec and query functions will raise errors if your SQL code has errors or there was an error with the database query itself.
It’s possible that if there’s a problem with communication to the database other Nakama core functions could also throw errors but each Lua function called is run in a short lived VM execution that cannot crash the server. If you don’t want to capture and handle those errors it’s fine. I would guard against them as a form of defensive programming but its a style you can choose.