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

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

Powered by : @r_channels & @reddit2telegram
Download Telegram
My nifty alternation pattern function

Sometimes you write a bit of code that makes you smile. This is my mine this week.

Lua patterns are awesome, but one thing I constantly miss from them is 'alternations', which means possible choices more than a character long. In PCRE regex these are notated like this: (one|two) three. But PCRE libraries are big dependencies and aren't normal Lua practice.

I realised that the {} characters are unused by Lua pattern syntax, so I decided to use them. I wrote a function which takes a string containing any number of blocks like {one|two} plus {three|four} and generates an array of strings describing each permutation.

function multipattern(patternWithChoices)
local bracesPattern = "%b{}"
local first, last = patternWithChoices:find(bracesPattern)
local parts = {patternWithChoices:sub(1, (first or 0) - 1)}

while first do
local choicesStr = patternWithChoices:sub(first, last)
local choices = {}

for choice in choicesStr:gmatch("(^|{}+)") do
table.insert(choices, choice)
end

local prevLast = last
first, last = patternWithChoices:find(bracesPattern, last)
table.insert(parts, choices)
table.insert(parts, patternWithChoices:sub(prevLast + 1, (first or 0) - 1))
end

local function combine(idx, str, results)
local part = partsidx

if part == nil then
table.insert(results, str)
elseif type(part) == 'string' then
combine(idx + 1, str .. part, results)
else
for , choice in ipairs(part) do
combine(idx + 1, str .. choice, results)
end
end

return results
end

return combine(1, '', {})
end

Only 35 lines, and it's compatible with Lua pattern syntax - you can use regular pattern syntax outside or within the alternate choices. You can then easily write functions to use these for matching or whatever else you want:

local function multimatcher(patternWithChoices, input)
local patterns = multipattern(patternWithChoices)

for
, pattern in ipairs(patterns) do
local result = input:match(pattern)
if result then return result end
end
end

Hope someone likes this, and if you have any ideas for improvement, let me know!

https://redd.it/1do731x
@r_lua
Beginner tutorials?

Hey I basically just learned about this language because I want to start to mod a game called Trailmakers. I basically have no coding background. Are there any good tutorials that start from the ground up? And is there any tips you'd like to share? Thanks.

https://redd.it/1doqat4
@r_lua
How do I fix this error
https://redd.it/1dp89wr
@r_lua
Having a simple syntax error would appreciate help.

I'm trying to make a probability calculator but I'm not very experienced with programming. The line is

odds = -1(1-(1/chance))^count

but it's giving me a syntax error with the Exponent Operator. I'm sure there's multiple things I'm doing wrong though. I'm otherwise done with my noscript besides I can't get this thing to shoot out a decimal at me. I'd appreciate any assistance

https://redd.it/1dqktcw
@r_lua
How do I make a word repeat, but before it repeats the user must type it and only then repeat it?

Hello

I'm learning lua and I'm having problems with my code. I want to make the phrase You lose. Type another number I want it to repeat, but the user must type first before the word is repeated, but what's happening is that the phrase repeats infinitely. How can I correct this?

print("Each round a number from 1 to 10 will be generated and you must guess it.")
local randomNumber = math.random(1, 10)

print("Type a number 1 to 10")
local guess = tonumber(io.read())

if guess == randomNumber then
print("You won!")
elseif guess ~= randomNumber then
repeat
print("You lose. Type anothor number")
until guess == randomNumber
else
print("Please type a natural number")
end

https://redd.it/1dqlazp
@r_lua
Combining Two Functions

I am brand new to Lua and would like to noscript something. I tried multiple methods of if else statements and nothing worked....

I tried changing the variables and so on...

Here is the code.


local key

function OnEvent(event, arg, family)
if event == "MOUSEBUTTONPRESSED" and arg == 10 then
key = key == "3" and "4" or "3"
PressKey(key)
Sleep(15)
ReleaseKey(key)
end
end


I would simply like to duplicate this so :

local key

function OnEvent(event, arg, family)
if event == "MOUSEBUTTONPRESSED" and arg == 10 then
key = key == "3" and "4" or "3"
PressKey(key)
Sleep(15)
ReleaseKey(key)
end
end

local key

function OnEvent(event, arg, family)
if event == "MOUSEBUTTONPRESSED" and arg == 12 then
key = key == "2" and "5" or "2"
PressKey(key)
Sleep(15)
ReleaseKey(key)
end
end

https://redd.it/1dqwknz
@r_lua
Any good tutorials for making games on Roblox?

I got basic-level knowledge of LUA. I've made small mods for a game (Project Zomboid) but that's looking at other's codes to get inspiration. I don't really know how to make something from scratch without looking at anything else first. Any good YouTube tutorials/online courses? Thanks!

https://redd.it/1drpaaz
@r_lua
Adding a extra image into layout

Sorry if i don't get things right / terminology plus the right place to post but i'm trying to add a extra image into a layout (jivelite) https://github.com/ralph-irving/jivelite/blob/master/share/jive/applets/JogglerSkin/JogglerSkinApplet.lua

Thing i'm trying to do is add a extra image ie a frame a .png which sit's above the album cover which gives the effect that the album cover has rounded corners as from reading .lua doesn't have libraries for image manipulation plus that over my head and i will put my hands up i'm a bit thick when i comes to this type of stuff so want to keep it easy so my brain cell can understand, but for the love of god i can't even workout how to add the extra image :(

I've placed the frame.png image into the the players icons folder it's just adding the extra code needed into the layout i have no clue about

Somehow over the last year or two i workout how to change bits of code to change the layout to get the look i was after see example of player below

https://i.postimg.cc/5y8Bmx54/GQL-MZAWAAAWRl-M.jpg







https://redd.it/1dry5w6
@r_lua
Can a lua noscript be decrypted if it is online and expired? I tried converting it to hexadecimal and then converting it to text but I failed. I'm not a programmer.



https://redd.it/1ds3hyg
@r_lua
Scatter slots

Currently working on a slot game that is 5 columns x 3 rows. 2 symbols that are adjacent win a 2x the amount, 3 symbols that are placed anywhere wins a different bonus. I'm running into and issue where I keep getting 2 symbols adjacent and 1 symbol scattered counting as the 2x win instead of the bonus. How could I write code that will help with not counting it as 2x pay win?

https://redd.it/1dsuqhm
@r_lua
Do you have a website for lua exercises?

Do you have a website for moon exercises?
I'm learning lua and I'd like to know some sites to do exercises on, since lua isn't a very well-known language compared to others like Python or JavaScript, there isn't much content on it. If anyone knows of any sites, I'd be grateful if you could tell me.

https://redd.it/1dt952p
@r_lua
Question about "require" feature.

Let's say i have two files. "Blocks.lua" and "Star.lua". I use the "require" to use variables from Star.lua in Block.lua

Now... how am i supposed to call the variables from Star.lua?

The variables in Blocks.Lua start with the "self.", that's understandable. But what should stand at the begining of variables taken from Star.lua? I can't start them with "self." as well, can i?



https://redd.it/1dtl7cu
@r_lua
Images/Sprites

Hello, first time posting. I am trying to start a personal project, very basic, I am learning all by myself but I am struggling with images, so far I am doing this:

_G.love = require("love")


local upperBackground = love.graphics.newImage('upperbackground.png')
local lowerBackground = love.graphics.newImage('lowerbackground.png')
function love.load()
   
    sprite = love.graphics.newImage ('sprites/upperbackground.png')
    sprite = love.graphics.newImage ('sprites/lowerbackground.png')

    UPPERBACKGROUND_WIDTH, UPPERBACKGROUND_HEIGHT=720,720
    LOWERBACKGROUND_WIDTH, LOWERBACKGROUND_HEIGHT=720,720

    function  love.keypressed(key)
        if key == "escape" then
            love.event.quit()
        end
    end
   
end

function love.update(dt)

end

function love.draw()
    love.graphics.draw(upperBackground, 0,0)
    love.graphics.draw(lowerBackground, 0,0)
 
   
end



Everytime I try to get it to work it says:

Error



main.lua:4: Could not open file upperbackground.png. Does not exist.





Traceback



\[love "callbacks.lua"\]:228: in function 'handler'

\[C\]: in function 'newImage'

main.lua:4: in main chunk

\[C\]: in function 'require'

\[C\]: in function 'xpcall'

\[C\]: in function 'xpcall'

I don't know what I am doing wrong, I specifically made a dooodle as a background, I put it in the sprites folder but lua keeps showing the error. Please help? And thanks in advance!

https://redd.it/1dty8lc
@r_lua
Functions (closures) and memory allocations

I am using Lua in a memory constrained environment at work, and I wanted to know how expensive exactly are functions that capture some state in Lua? For example, if I call myFn:

local someLib = require('someLib')
local function otherStuff(s) print(s) end

local function myFn(a, b)
return function()
someLib.call(a)
someLib.some(b)
otherStuff('hello')
return a + b
end
end

How much space does the new function take? Is it much like allocating an array of two variables (a and b), or four variables (a, b, someLib and otherStuff) or some other amount more than that?

https://redd.it/1dur0ku
@r_lua
Notes/Listing system in Lua (outside Roblox Studio) with Guides

-- See Code below for guide

local function clear()
for i = 1, 100 do
print()
end
end

local list = {}

local function reloadList()
if #list > 0 then
for _, listed in ipairs(list) do
if listed[2] == "bool" then
if listed[3] == "true" then
print(" "..listed[1].." 🟩")

elseif listed[3] == "false" then
print(" "..listed[1].." 🟥")
end

elseif listed[2] == "num" then
print(" "..listed[1].." 🧱"..listed[3].." / "..listed[4].."🧱")
end
end
end

for i = 1, 11 - math.min(#list, 11) do
print()
end
end

local ListPatternBool = "/List%s(.+)%s(%a+)%s(%a+)"
local ListPatternNum = "/List%s(.+)%s(%a+)%s(%d+)%s(%d+)"

local SetPatternBool = "/Set%s(.+)%s(%a+)"
local SetPatternNum = "/Set%s(.+)%s(%d+)%s(%d+)"

local RemovePattern = "/Remove%s(.+)"

local function write()
local input = io.read()

clear()

if input then
local name, listType, bool = input:match(ListPatternBool)
local name2, listType2, num, max = input:match(ListPatternNum)
local name3, value = input:match(SetPatternBool)
local name4, value2, maxValue = input:match(SetPatternNum)
local name5 = input:match(RemovePattern)

if #list < 11 and name and listType and listType:lower() == "bool" and bool and (bool:lower() == "true" or bool:lower() == "false") then
local existing = false

if #list ~= 0 then
for _, listed in ipairs(list) do
if not existing and listed[1] and listed[1] == name then
existing = true
end
end
end

if not existing then
table.insert(list, {name, "bool", bool})
end

elseif #list < 11 and name2 and listType2 and listType2:lower() == "num" and num and max then
local existing = false

if #list ~= 0 then
for _, listed in ipairs(list) do
if not existing and listed[1] and listed[1] == name2 then
existing = true
end
end
end

if not existing then
table.insert(list, {name2, "num", math.min(num, max), max})
end

elseif name3 and (value:lower() == "true" or value:lower() == "false") then
local changed = false

if #list ~= 0 then
for _, listed in ipairs(list) do
if not changed and listed[1] == name3 and listed[2] == "bool" then
changed = true

listed[3] = value
end
end
end

elseif name4 and value2 and maxValue then
local changed = false

if #list ~= 0 then
for _, listed in ipairs(list) do
if not changed and listed[1] == name4 and listed[2] == "num" then
changed = true

listed[4] = maxValue
listed[3] = math.min(value2, listed[4])
end
end
end

elseif name5 then
if #list ~= 0 then
for i, listed in ipairs(list) do
if listed[1] == name5 then
table.remove(list, i)
end
end
end
end
end

if input then
reloadList()
write()
end
end

write()

-- List --
-- Boolean (true/false): /List name bool value
-- Number (num/max): /List name num value maxValue
--|--

-- Changes --
-- Boolean (true/false): /Set name value
-- Number (num/max): /Set name value maxValue
-- Remove: /Remove name
--|--

https://redd.it/1dv7dbi
@r_lua
How to learn lua

I want to start learning code because I want to start making games on Roblox and are there any websites or tutorials that I can watch to help me learn coding?

https://redd.it/1dvchce
@r_lua
How do i learn lua, (what are good places to learn)

i tried learning c# first but quit, python is decent but i want this one, what are good websites or videos to learn it. im tryna help my friends on making a game (not roblox)

https://redd.it/1dve2nw
@r_lua
👍1
Optional function annotation?

I can't seem to figure out how to mark a function as optional, here is a short example:

---@meta
---@class FrameContainer
---@field Frame table the container frame.
---@field Type number the type of frames this container holds.
---@field LayoutType number the layout type to use when arranging frames.
---@field FramesOffset fun(self: table): Offset? any offset to apply for frames within the container.
---@field GroupFramesOffset fun(self: table): Offset? any offset to apply for frames within a group.


I wish to make the FramesOffset and GroupFramesOffset functions nullable/optional but unsure how. I've tried adding a "?" in various locations but it results in a syntax error.

https://redd.it/1dvlquc
@r_lua
Resetting system state in between luaunit tests

I have a bunch of automated tests that end up modifying system state. I'm manually unwinding state changes inside my `teardown()` function however it's very bothersome to do this and I have a feeling not all changes are being reset.

My question is: is there a nicer way to reset state during tests? I suppose I could run a separate lua process for every single test but hoping there is a cleaner solution?

Here is the source code: https://github.com/Verubato/framesort/blob/main/tests/Test.lua

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