"Right tool for the right job" is an exaggareted statement.
Hello there !
In this post I want to express my opinions about current software development practices + some little ranting about it.
As the noscript says, we're used to be told that out there we have specialized programming languages for many areas of development, we have JavaScript for web, we have C# for games and Python for machine learning.
Right tool for the right job, right? Well, I couldn't disagree more. Most of these "industry standards" come mostly from popularity and trends alone and it rarely has anything to do with actual efficiency and technical decisions.
Take JavaScript for example. It is a complete disaster for the web and even for software development. Instead of having simple HTML pages that are rendered and sent by the server, they put all the rendering and data gathering on the client with silly and over-engineered JS noscripts that I find completely unnecessary. What does a website do specially compared to it's 10 years old version? Websites today put hassle on even strong computers with the amount of resources they consume. And let's not mention ElectronJS apps, that are so much worse than native alternatives written in Java or other languages.
What does that have to do with Lua? I recently discovered Lua through game development and I can't believe how capable it is of doing many things like backends with Lapis or other stuff. The overhead is so little, the syntax is so easy and the JIT is blazingly fast, reaching even C-like performance in some scenarios.
I've built stuff in Lua, from games, to SSR-ed websites and machine learning algorithms. I might agree the ecosystem is not as huge and documented or full of features like other languages, but it has enough for what most startups or individuals are aiming for, that while keeping a small overhead footprint, fast performance and rapid prototyping.
I am not necessarily trashing on other languages (except JavaScript which ruined performance and forces people to buy new computers due to it's trash performance and huge overhead) but Lua deserved a better spot and more popularity. I find it highly capable and in combination with C it's probably, in my eyes, the greatest GPL out there. Prior to switching to Lua, I was an avid user of Python and Java. Python is my first love, allowed me learn programming and web development, but it's limitations and overhead started to become more clearer and unsettling for me the more experience I've got. Java is also great, fast, and forces people to organize their code well. But coding in Java is not as fast and fun as doing it in Python or Lua.
If I were to choose, my toolbox would include C, Lua and Java but sadly I am forced to work with JS and respect my superior's orders to respect deadlines and ignore optimization by writing tons of glue and spaghetti code.
https://redd.it/1hms0k0
@r_lua
Hello there !
In this post I want to express my opinions about current software development practices + some little ranting about it.
As the noscript says, we're used to be told that out there we have specialized programming languages for many areas of development, we have JavaScript for web, we have C# for games and Python for machine learning.
Right tool for the right job, right? Well, I couldn't disagree more. Most of these "industry standards" come mostly from popularity and trends alone and it rarely has anything to do with actual efficiency and technical decisions.
Take JavaScript for example. It is a complete disaster for the web and even for software development. Instead of having simple HTML pages that are rendered and sent by the server, they put all the rendering and data gathering on the client with silly and over-engineered JS noscripts that I find completely unnecessary. What does a website do specially compared to it's 10 years old version? Websites today put hassle on even strong computers with the amount of resources they consume. And let's not mention ElectronJS apps, that are so much worse than native alternatives written in Java or other languages.
What does that have to do with Lua? I recently discovered Lua through game development and I can't believe how capable it is of doing many things like backends with Lapis or other stuff. The overhead is so little, the syntax is so easy and the JIT is blazingly fast, reaching even C-like performance in some scenarios.
I've built stuff in Lua, from games, to SSR-ed websites and machine learning algorithms. I might agree the ecosystem is not as huge and documented or full of features like other languages, but it has enough for what most startups or individuals are aiming for, that while keeping a small overhead footprint, fast performance and rapid prototyping.
I am not necessarily trashing on other languages (except JavaScript which ruined performance and forces people to buy new computers due to it's trash performance and huge overhead) but Lua deserved a better spot and more popularity. I find it highly capable and in combination with C it's probably, in my eyes, the greatest GPL out there. Prior to switching to Lua, I was an avid user of Python and Java. Python is my first love, allowed me learn programming and web development, but it's limitations and overhead started to become more clearer and unsettling for me the more experience I've got. Java is also great, fast, and forces people to organize their code well. But coding in Java is not as fast and fun as doing it in Python or Lua.
If I were to choose, my toolbox would include C, Lua and Java but sadly I am forced to work with JS and respect my superior's orders to respect deadlines and ignore optimization by writing tons of glue and spaghetti code.
https://redd.it/1hms0k0
@r_lua
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
I'm building an isometric toolkit for making games in Lua
Lua isometric toolkit demo
I have always wanted to make a game in the style of Final Fantasy Tactics. They are some of my favourite styles of games to play. There seems to be a lost of art making that style of games with very few games coming out anymore that are in that style. The goal of the toolkit is to make it a lot easier to get started with that style of game.
Part of building the toolkit is to also help me learn some of the basic game dev concepts. I'm a web developer by trade, so understanding how to draw graphics is a big mental shift.
The code is also fully tested and written with full docblocks for each method and property. I usually implement new features using TDD given how easy it is with this setup.
Another goal of the project is to make it possible to make isometric games with any Lua game framework. Right now, the demo is in Love2d. But given the "event driven" nature of the base components, you can implement your own "draw" event for each tile. You can also supply your own bounding box and hit box.
The code is also written with Z position in mind. So eventually there should be a way to do path calculation that takes into account the "height" of the tile. Right now, the demo just takes advantage of the separated world position and grid position to emulate heights by putting a tile in a "higher" world position but keeping it in the same grid position. So the code sees it as a neighbour.
It is still a work in progress. My next features are area of effect (like archer and magic attacks in FFT) and then I want to implement a basic "character" that has properties that affect movement as well as a "turn queue" that also takes into consideration those properties.
https://redd.it/1ho9jed
@r_lua
Lua isometric toolkit demo
I have always wanted to make a game in the style of Final Fantasy Tactics. They are some of my favourite styles of games to play. There seems to be a lost of art making that style of games with very few games coming out anymore that are in that style. The goal of the toolkit is to make it a lot easier to get started with that style of game.
Part of building the toolkit is to also help me learn some of the basic game dev concepts. I'm a web developer by trade, so understanding how to draw graphics is a big mental shift.
The code is also fully tested and written with full docblocks for each method and property. I usually implement new features using TDD given how easy it is with this setup.
Another goal of the project is to make it possible to make isometric games with any Lua game framework. Right now, the demo is in Love2d. But given the "event driven" nature of the base components, you can implement your own "draw" event for each tile. You can also supply your own bounding box and hit box.
The code is also written with Z position in mind. So eventually there should be a way to do path calculation that takes into account the "height" of the tile. Right now, the demo just takes advantage of the separated world position and grid position to emulate heights by putting a tile in a "higher" world position but keeping it in the same grid position. So the code sees it as a neighbour.
It is still a work in progress. My next features are area of effect (like archer and magic attacks in FFT) and then I want to implement a basic "character" that has properties that affect movement as well as a "turn queue" that also takes into consideration those properties.
https://redd.it/1ho9jed
@r_lua
I made a tiny library for switches and sum types in Lua.
https://github.com/alurm/lua-match
https://redd.it/1hphljb
@r_lua
https://github.com/alurm/lua-match
https://redd.it/1hphljb
@r_lua
GitHub
GitHub - alurm/lua-match: Minimalistic sum types and switches for Lua
Minimalistic sum types and switches for Lua. Contribute to alurm/lua-match development by creating an account on GitHub.
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
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
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
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
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
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
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
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
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
GitHub
GitHub - emilrueh/lua-genai at dev
Lua interface for working with multiple generative AI providers - GitHub - emilrueh/lua-genai at dev
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:
The monitor:
Call to add_line()
https://redd.it/1hrc1rh
@r_lua
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 6printh("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 monitornew=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 doprint(self.lines[i+1],left_margin,top_margin+i*line_height,7)endend}Call to add_line()
eoum.add_line("finalbx:"..bl.x)https://redd.it/1hrc1rh
@r_lua
Pastebin
argument is nil inside function in table - Pastebin.com
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Prosody 0.12.5 released - An XMPP/Jabber server written in Lua
https://blog.prosody.im/prosody-0.12.5-released/
https://redd.it/1hrge5g
@r_lua
https://blog.prosody.im/prosody-0.12.5-released/
https://redd.it/1hrge5g
@r_lua
blog.prosody.im
Prosody 0.12.5 released
We are pleased to announce a new minor release from our stable branch.
Hope everyone has had a good 2024, and you’re looking forward to a better 2025!
We’re ending this year with a bugfix release for our stable 0.12 branch. This brings some general polish…
Hope everyone has had a good 2024, and you’re looking forward to a better 2025!
We’re ending this year with a bugfix release for our stable 0.12 branch. This brings some general polish…
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
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
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
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
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
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
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
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
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
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
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
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
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
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
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
Gist
My first try to implement Dijkstra's algorithm in Lua. Feedback welcome!
My first try to implement Dijkstra's algorithm in Lua. Feedback welcome! - dijkstra.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](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 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
Gist
My first try to implement Dijkstra's algorithm in Lua. Feedback welcome!
My first try to implement Dijkstra's algorithm in Lua. Feedback welcome! - dijkstra.lua
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
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
Reddit
From the lua community on Reddit: Feedback on my Dijkstra implementation
Explore this post and more from the lua community
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
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
Reddit
From the lua community on Reddit
Explore this post and more from the lua community
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
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
Reddit
From the lua community on Reddit
Explore this post and more from the lua community