Lua - Reddit – Telegram
Lua - Reddit
31 subscribers
281 photos
31 videos
4.27K links
News and discussion for the Lua programming language.

Subreddit: https://www.reddit.com/r/lua

Powered by : @r_channels & @reddit2telegram
Download Telegram
Managing locks in Lua: pcall or xpcall?

Hi everyone,

I’m working on a Lua project where I need to manage locks around critical sections of code - that's because I got several Lua states that may live in separate threads, and sometimes they operate on a shared data. I’ve implemented a doWithLock function that acquires a lock, executes a function, and ensures the lock is released, even if an error occurs. However, I’m trying to decide between two approaches: using pcall or xpcall for error handling.

Here’s what the two approaches look like:

Approach 1: Using pcall (simple and straightforward)

doWithLock = function(object, func, ...)

local handle = object.___id
jclib.JLockMgr_acquireLock(LuaContext, handle)
local ok, result = pcall(func, ...)
jclib.JLockMgr_releaseLock(LuaContext, handle)

if not ok then
error(result)
end

return result
end



Approach 2: Using xpcall

In this approach, I’ve corrected it to ensure the lock is only released once, even if both the error handler and the normal flow attempt to release it.

doWithLock = function(object, func, ...)

local handle = object.___id
local lockReleased = false
-- Track whether the lock has been released
jclib.JLockMgr_acquireLock(LuaContext, handle)
local function releaseLockOnError(err)
if not lockReleased then
jclib.JLockMgr_releaseLock(LuaContext, handle)
lockReleased = true
end
error(err, 2)
end

local ok, result = xpcall(func, releaseLockOnError, ...)

if not lockReleased then
jclib.JLockMgr_releaseLock(LuaContext, handle)
lockReleased = true
end

return result

end

My Questions: 1. Is there any practical benefit to using xpcall in this situation, given that the error handler is very simple (it just releases the lock and rethrows the error)? No additional logging in the erorr handler and etc. 2. Is xpcall approach is better in the long term? 3. Does reddit support Markdown? :D

https://redd.it/1hpt0s0
@r_lua
Tips on Starting

Just bought the lua book and started also looking at tutorials online, kinda understand what im getting into but i don't. My main question is how do i go about creating my own custom functions or noscripts whenever I'm making something for a game..like how do i come up with my own noscripts if this make sense..what is the thought process or approach.. and also any tips on how to learn lua and roblox maybe im going about it wrong.

https://redd.it/1hq532w
@r_lua
Why doesn't my code work? I rewrote it from the book but I can't get it to work.
https://redd.it/1hr4oiw
@r_lua
I'm building a basic OpenAI and Anthropic SDK for Lua

Been working for the past month building an interface to simplify working with multiple generative AI providers and published a first release with support for OpenAI and Anthropic, with Gemini as well as open-source models planned for future updates.

Major features like streaming responses and an abstraction layer collecting message histories are already implemented and I'll keep actively developing the package which is available on luarocks.

local genai = require("genai")

local client = genai.new("<YOURAPIKEY>", "https://api.openai.com/v1/chat/completions")

local chat = client:chat("gpt-4o-mini")
print(chat:say("Hello, world!"))

The code base is intended to be modular, readable, and maintainable to allow easy collaboration. I intend this package to become the easiest interface for all AI needs in Lua, possibly with a focus on gamedev.

https://github.com/emilrueh/lua-genai/tree/dev

Please have a look and let me know what you think about this idea!

Is the code structured well for your use-cases? Will this make someone's life easier? Did you spot any obvious downfalls?

https://redd.it/1hrc3pb
@r_lua
Value of argument is nil inside function (within a table) --- PICO-8

EDIT: Code is pasted below and at https://pastebin.com/zMH50zs4

I'm creating a monitor so I can see some variables changing in real time in my game. The monitor has the function add_line(). So I can pick a variable wherever and add it to the monitor.

The add_line() argument called lin is supposed to print but isn't. With a printh I see its value is nil. I can't find anything online that talks about passing arguments to a function within a table. I'm thinking I have a syntax error somewhere.

The code I'm monitoring works perfectly, so I know that's not the problem. I'm setting up this monitor for the inevitable bugs to come.

Below I have the error, the monitor object and the call to add_line(). Thanks in advance for any help. (The code block feature for this post isn't working for some reason, so I'm pasting as inline code.)

Here's the error:

runtime error line 22 tab 6

printh("in add_line, lin="..lin,"bugfile.txt")

attempt to concatenate local 'lin' (a nil value)

at line 0 (tab 0)

The monitor:

monitor={

left_margin=3,

top_margin=3,

line_height=7,

lines={},--text on monitor

new=function(self,tbl)

tbl=tbl or {}

setmetatable(tbl,{

__index=self

})

return tbl

end,

add_line=function(self,lin)

printh("in add_line, lin="..lin,"bugfile.txt")*******Error******

add(self.lines,lin)

end,

draw=function(self)

for i=0,#self.lines-1 do

print(self.lines[i+1],left_margin,top_margin+i*line_height,7)

end

end

}

Call to add_line()

eoum.add_line("finalbx:"..bl.x)

https://redd.it/1hrc1rh
@r_lua
What makes Lua especially embeddable?

Whenever the topic of Lua comes up, I always here people say that it's very easy to embed. This is supposedly why it's used so often in game programming. But I don't know what people mean when they say it's easy to embed. What makes it so easy. What does it even mean to embed a language? What things make a given language easy or hard to embed?

https://redd.it/1hrlvr9
@r_lua
Newbie: Output in a Terminal

I have Love2d up and running in VS code and I'm able to launch my games through keyboard shortcuts, and dragging and dropping onto the application. I'm to a point though that I want to start debugging and can't figure out how to do so. I'm still learning how to make love.draw() work consistently but it would be much easier if I could see outputs in a terminal. I come from programming in Java, C++, Python, etc. In the IDEs I use for those, a print() statement will just output to the terminal, is there anything for Love2d projects? I'm using VS code for the IDE

https://redd.it/1hsb0kj
@r_lua
random on lua

i'm using lua to noscript commands on mpv- my goal is to simulate television but only with my fav shows and no ads. i use it to waste time and mostly as a noise background but lately i'm noticing that random is repetitive!

**what i'm doing**: since my attention span is hella short i did some coding to have only 1-2 minutes of each video then jump at the next one in queue (that's the same or different tv series) and re-add the previous to the end so only the selected shows play. it's a bit more complicated than this but i hope i explained myself.

**getting to the point**: when i'm adding a "*random*" video i'm doing `math.randomseed(os.time())` looking for another episode of the same series that could be prev season, current season or next season. most shows have 10 or 20 episodes each season, so i'm having a range of 1-60

but i found that too many times i get the same number (and therefore episode) with several minutes apart each roll. then it changes for each session or after a while, i mean it gets more likely to give me a different series of episodes for each show.

let me be clear, it's not ALWAYS the same but looks like the pseudo random is too much of a pseudo and not enought of a random if that makes any sense XD any advice on how to approach random get function and random seeds? here's how i'm doing it right now (right after setting the seed)

local next_file = files[math.random(#files)]

where files is the collection of \~60 episodes path

thanks for reading have a great day

https://redd.it/1htcbsa
@r_lua
Lua noscript for streamavatar

I am a new comer in lua coding!
I have managed to connect both of them together using ,streamavatar websocket codes.
I had been trying to use lua noscript that streamavatar to request for "commands" in streamerbot and it's not working no matter how I try it.
I tried asking the developer but they say do it yourself

https://preview.redd.it/yurvx99701be1.png?width=882&format=png&auto=webp&s=7d8844ee7432da75cc8232a1c4ab93db3d8e22a3

https://preview.redd.it/xyd84ab501be1.png?width=716&format=png&auto=webp&s=0758603081d38283d7ffc9ace521a04302017ab0

So I am here asking if anyone can guide me on how it works?

https://redd.it/1htlrn4
@r_lua
Security questions

I want to make a app in lua. (Using love2d) This app will handle sending money through Paypal or other payment methods and withdrawals of the Paypal business account to other PayPal accounts. What are so security practices to do this in the most secure way to ensure that no one will be able to access other users Paypal and take out all of the playpal business account? Should I use a different program like love2d that supports payments?

https://redd.it/1htoz18
@r_lua
Feedback on my Dijkstra implementation

While I was doing Advent of Code (in Ruby) last month I found out that I can't implement Dijkstra on the fly (so I didn't managed day 16), so thought it was an excellent opportunity to try it in Lua for a little Love2d-game.

Since it's my first time with this algorithm and with Metatables in Lua I would love some feedback on my code.

The code is written from the Wikipedia explanation of the algorithm.

I'm looking for general feedback, but I have some questions.

\- On line 119 I'm not sure if this `if prev[u\] or u == source then` is really necessary.
\- On line 16 I define the `self.__index`, I tried to make it so that you could make a new Node with known x/y and look it up in a table, but couldn't get it to work. For source/target I needed to use `for k,v in...`in stead of `table[source\]` to find the correct node. That's why I have the two functions `findKey()` and `setTo()`.

I've made a Gist too: https://gist.github.com/Kyrremann/120fcbdd032a7856059960960645e0b9

require("math")

local Dijkstra = {
nodes = {},
}

local Node = {}

function Node:new(x, y)
local node = {
x = x,
y = y,
}

setmetatable(node, self)
self.index = self

return node
end

--- This is for pretty debugging
Node.tostring = function(self)
return self.x .. "," .. self.y
end

Node.eq = function(a, b)
return a.x == b.x and a.y == b.y
end

--- Takes a Tiled map file as input, but any matrix with properties.weight should work.
function Dijkstra:init(map)
for y = 1, #map do
for x = 1, #mapy do
local node = Node:new(x, y)
self.nodesnode = mapyx.properties.weight
end
end
end

--- Finds the distance between two tiles in the map
-- @param source A table with x and y
-- @param target A table with x and y
function Dijkstra:calculate(source, target)
source = Node:new(source.x, source.y)
target = Node:new(target.x, target.y)

local function findKey(t, k)
for key, in pairs(t) do
if key == k then
return key
end
end
end

local function setTo(t, k, v)
local key = findKey(t, k)
if not key then
error("Key: " .. tostring(k) .. " not found")
end
t[key] = v
end

local function shortestDistance(queue, distances)
local found = nil
local min = math.huge

for key, dist in pairs(distances) do
if queue[key] and dist < min then
min = dist
found = key
end
end

if not found then
error("Shortest distance not found")
end

return found
end

local function getNeighbors(node, queue)
local ortho = {
Node:new(node.x, node.y - 1),
Node:new(node.x, node.y + 1),
Node:new(node.x - 1, node.y),
Node:new(node.x + 1, node.y),
}

local neighbors = {}
for i = 1, 4 do
if findKey(queue, ortho[i]) then
table.insert(neighbors, ortho[i])
end
end

return neighbors
end

local dist = {}
local prev = {}
local queue = {}
local queueSize = 0

for k,
in pairs(self.nodes) do
distk = math.huge
prevk = nil
queuek = k
queueSize = queueSize + 1
end

setTo(dist, source, 0)

while queueSize > 0 do
local u = shortestDistance(queue, dist)

if u == target then
local path = {}
local weight = 0

if prevu or u == source then
Feedback on my Dijkstra implementation

While I was doing Advent of Code (in Ruby) last month I found out that I can't implement Dijkstra on the fly (so I didn't managed day 16), so thought it was an excellent opportunity to try it in Lua for a little Love2d-game.

Since it's my first time with this algorithm and with Metatables in Lua I would love some feedback on my code.

The code is written from the Wikipedia explanation of the algorithm.

I'm looking for general feedback, but I have some questions.

\- On line 119 I'm not sure if this \`if prev\[u\] or u == source then\` is really necessary.
\- On line 16 I define the \`self.\_\_index\`, I tried to make it so that you could make a new Node with known x/y and look it up in a table, but couldn't get it to work. For source/target I needed to use \`for k,v in...\`in stead of \`table\[source\]\` to find the correct node. That's why I have the two functions \`findKey()\` and \`setTo()\`.

I've made a Gist too: [https://gist.github.com/Kyrremann/120fcbdd032a7856059960960645e0b9](https://gist.github.com/Kyrremann/120fcbdd032a7856059960960645e0b9)

require("math")

local Dijkstra = {
nodes = {},
}

local Node = {}

function Node:new(x, y)
local node = {
x = x,
y = y,
}

setmetatable(node, self)
self.__index = self

return node
end

--- This is for pretty debugging
Node.__tostring = function(self)
return self.x .. "," .. self.y
end

Node.__eq = function(a, b)
return a.x == b.x and a.y == b.y
end

--- Takes a Tiled map file as input, but any matrix with properties.weight should work.
function Dijkstra:init(map)
for y = 1, #map do
for x = 1, #map[y] do
local node = Node:new(x, y)
self.nodes[node] = map[y][x].properties.weight
end
end
end

--- Finds the distance between two tiles in the map
-- @param source A table with x and y
-- @param target A table with x and y
function Dijkstra:calculate(source, target)
source = Node:new(source.x, source.y)
target = Node:new(target.x, target.y)

local function findKey(t, k)
for key, _ in pairs(t) do
if key == k then
return key
end
end
end

local function setTo(t, k, v)
local key = findKey(t, k)
if not key then
error("Key: " .. tostring(k) .. " not found")
end
t[key] = v
end

local function shortestDistance(queue, distances)
local found = nil
local min = math.huge

for key, dist in pairs(distances) do
if queue[key] and dist < min then
min = dist
found = key
end
end

if not found then
error("Shortest distance not found")
end

return found
end

local function getNeighbors(node, queue)
local ortho = {
Node:new(node.x, node.y - 1),
Node:new(node.x, node.y + 1),
Node:new(node.x - 1, node.y),
Node:new(node.x + 1, node.y),
}

local neighbors = {}
for i = 1, 4 do
if findKey(queue, ortho[i]) then
table.insert(neighbors, ortho[i])
end
end

return neighbors
end

local dist = {}
local prev = {}
local queue = {}
local queueSize = 0

for k, _ in pairs(self.nodes) do
dist[k] = math.huge
prev[k] = nil
queue[k] = k
queueSize = queueSize + 1
end

setTo(dist, source, 0)

while queueSize > 0 do
local u = shortestDistance(queue, dist)

if u == target then
local path = {}
local weight = 0

if prev[u] or u == source then
while prev[u] do
table.insert(path, 1, u)
weight = weight + dist[u]
u = prev[u]
end
end

return path, weight
end

queue[u] = nil
queueSize = queueSize - 1

local neighbors = getNeighbors(u, queue)
for _, n in pairs(neighbors) do
local key = findKey(dist, n)
if not key then
error("Key: " .. tostring(key) .. " not found")
end

local alt = dist[u] + self.nodes[key]
if alt < dist[key] then
dist[key] = alt
prev[key] = u
end
end
end

error("Path not found")
end

return Dijkstra


https://redd.it/1htr0jf
@r_lua
How to reset a counter back to 0 in lua?

i am very new to lua and i am currently trying to create a program for my mc turtle, i have a if statement that tells it to count the steps it takes before doing a action. But after it has performed that action it should reset the counter to 0 again.

Not sure what i am doing wrong but it is not resetting it like it should.

local function Mine_Stairs()

local stepCount = 0

local torchCount = 0



while true do

turtle.dig()

if turtle.forward() then

stepCount = stepCount + 1

torchCount = torchCount + 1



turtle.digUp()

turtle.digDown()



if torchCount % 5 == 0 then --counts how many steps it has taken before it should place a torch.

local itemDetail = turtle.getItemDetail(16)

if itemDetail and itemDetail.name == "minecraft:torch" then



turtle.select(16)

turtle.forward()



turtle.turnRight()

turtle.turnRight()



turtle.place()

print("Torch placed.")



turtle.turnLeft()

turtle.turnLeft()



if count == torchCount and stepCount == 1 then

torchCount = torchCount - 1

stepCount = stepCount - 1

end

else

print("Out of torches!")

end

end



if stepCount % 3 == 0 then --counts how many steps it ahs taken before it should rotate to the right.

turtle.turnRight()

stepCount = 0

end



turtle.down()



else

print("Obstacle detected. Stopping.")

break

end

end

end



Mine_Stairs()



https://redd.it/1huynaz
@r_lua
Have you ever used this book to learn? Lua
https://redd.it/1hv88q8
@r_lua
why does Pairs sometimes puts it in order, but sometimes not?

I understand that Pairs() isn't guaranteed to go through "arrays" in order.

I have 3 tables below that are all numerically indexed starting from 1. I used different ways of making each table. I just want to know why tables B and C are in order with Pairs, but table A is NOT in order. (output is at the bottom of the post) All 3 tables are using pairs

For table A, does it have anything to do with explicitly defining the index number?

The IDE is visual studio Code.

A = {
    [1] = "one",
    [2] = "two",
    [3] = "three",
    [4] = "four"
}
for i, v in pairs(A) do
  print(i, v)
end

B = {"a", "b", "c", "d"}
for i, v in pairs(B) do
  print(i, v)
end

C = {}
for i=1, 9 do
    C[i] = i*10
end
for i, v in pairs(C) do
  print(i, v)
end

Output:

3 three
1 one
2 two
4 four
1 a
2 b
3 c
4 d
1 10
2 20
3 30
4 40
5 50
6 60
7 70
8 80
9 90

https://redd.it/1hvd7fr
@r_lua
Roblox Script not Working HELP!!

I am developing a game where you can tag a player on the other team as long as they are on your side and when tagged the other player is killed then respawned to a "jail" I have a remote event named "TagEvent" set up and the teams "Frosting" and "Dough" are set up as well with their separate spawnpoints called "FrostingTagged" and "DoughTagged". Also, the part where they get tagged is noscriptd is called "FrostingTagArea" and "DoughTagArea". These are all setup you can touch them and query them all as well. I've used Ai to help me, and it has done nothing to help. I am truly lost. Any ideas are appreciated. When i do a local server test the only two things that show up in the output are something along the lines of "no player found" and "Player 1 is attempting to tag Player 2". Ill include pictures of both of the noscripts.

Local Script

Server

Server

Server



https://redd.it/1hvcop3
@r_lua
Lua with Manual memory management

Hi everyone!

I’ve started experimenting with the Lua API in C, and I thought there was no better way to challenge myself than by implementing a manual memory management system in Lua.

I just wanted to share the current state of the project. As of now, it’s not working as smoothly as I’d like. Currently, you still need to explicitly use the garbage collector (GC) to delete freed pointers, and I’ve only implemented integer types so far. But hey, I’m closer than I was yesterday, so I’ll keep improving the project.

Feel free to check it out, discuss, critique my code, open issues, or make pull requests (PRs).

At the moment, it doesn’t include a method to compile the library or even a simple release, as, like I mentioned, it’s not fully functional yet.

For anyone wondering: Why??????
Well, I just wanted to do it. There’s no particular scenario where this would be better than Lua’s original garbage collector—especially considering you can trigger the GC manually—but hey, I’m just a simple guy who likes to mess around with things.

I hope some of you find the idea interesting.

GitHub Repository: Unsafe-Lua


https://redd.it/1hvra76
@r_lua