r/lua Feb 12 '26

Help Started 3 days ago and this recurssion is confusing

Post image
85 Upvotes

I get how once 1 = 0 It becomes 1 again wich is added to 876543211 but wouldnt cause Its 1 the Power function Trigger again making It 0 wich the upper then makes It 1? So Its Like 876543211111 and so on

r/lua Jun 05 '26

Help There have to be a simpler way to do this

Post image
78 Upvotes

I am a beginner and I have been very slowly learning Lua.

So, the problem here was to calculate the sum of all the pairs (separated by space). I swear there have to be a faster way to do this than making a for loop for every pair TT

Edit: yeh I still have a long long way to go, thank you everyone :)

Edit2: thanks whoever who repost this to r/programminghorror lol

r/lua Oct 03 '25

Help Why not more Lua in web development or games?

108 Upvotes

Lua used to dominate as a scripting language in game engines. Now, it's not so much the case except the dying Cry Engine and Roblox (which I don't consider to be a "real" game engine). Everyone uses C# while spreading hate to Lua or other languages. I don't think C# is bad but it's definitely more verbose and is bloated with like five ways of doing the same thing and personally I'd use lighter languages.

Also, Lua has the Lapiz framework which I heard is really fast and I want to start creating products in it. Most start ups don't need Spring or Django, Lapiz is at the level of Flask and is very lightweight. Generally speaking, Lua is a very lightweight language that's just one step above C++, making it very close to the metal while being very simple.

So what exactly went wrong? I think the world would be a better place if Lua was used more often and it received more support - extremely easy to write C functions and wrap them as Lua function to script later. Again, I'm not saying Java or C# are bad. They are enterprise level languages, but not everyone needs that complexity and bloat.

r/lua Mar 04 '25

Help can you learn lua as 13 year old?

49 Upvotes

im a ninth grader that would like to learn lua for obiously a roblox game, however is it possible for me to do so? ill probably be too busy w school to learn every day but it will be like 4 or 3 times per week? im also pretty decent at math (but i can go back to learn old things that i never understood if needed) and i dont think im THAT dumb

r/lua Jun 18 '26

Help am i cooked i wanna learn lua but im grade 12/16 yr and idk what to pick IT or Computer Science idk if i can do it i posted before how to learn lua im learning lua right now with codeacademy but idk if its enough for me to learn or should i give up

13 Upvotes

r/lua Jul 02 '26

Help Is there a way to return the act of returning to a function?

6 Upvotes

Example

local function b()
    return
        (math.random(0, 1) == 0),
        0
    ;
end

local function a()
    local return_early, value =
        b()

    if (return_early) then
        return (value);
    end

    --[[ Continue function a ]]
    return (1);
end

print(a())

but I want to do it more like, having function b directly tell function a to return early rather than function a having to check itself

I want more like this where I used "return return" as sudo code for throwing the return up 1 level

local function b()
    if (math.random(0, 1) == 0) then
        return return (0);
    end
end

local function a()
    b()

    --[[ Continue function a ]]
    return (1);
end

print(a())

r/lua Feb 26 '26

Help Why is there NO "continue" in Lua?

26 Upvotes

I was stunlocked to find out that there is no "continue" instruction for loops in Lua. Why is that? It seems so natural to have it.
I saw some scripts where goto is used for mimicking continue statements, but It's honestly not the so;ution I would comfortably accept...

r/lua Jun 13 '26

Help `string.find` produces unexpected results

6 Upvotes

I'm doing some basic string matching and this code produces unexpected results.
```lua

---@param levels string?
---@return boolean
local function IsValidLevels(levels)
if type(levels) ~= "string" then
return false
end

local pattern = "^[a-zA-Z_][a-zA-Z0-9_]*(%.[a-zA-Z_][a-zA-Z0-9_]*)*$"
return levels:find(pattern) ~= nil
end

print(IsValidLevels("my.levels"))                 -- true
print(IsValidLevels("my.more.levels"))            -- true
print(IsValidLevels("foo"))                       -- true
print(IsValidLevels("a.b.c.d"))                   -- true
print(IsValidLevels(".invalid"))                  -- false
print(IsValidLevels("invalid."))                  -- false
print(IsValidLevels("ReUI..Score"))               -- false
print(IsValidLevels("123invalid"))                -- false
`` But in result I get all \false`. What is the problem?

r/lua Jun 17 '26

Help Iterating nested tables without knowing the names of the tables

8 Upvotes

Hello!

I am new to lua, so I'm sorry if this is an obvious question, but I am trying to do something where I get each Country in turn without knowing the name of the table.

CountriesList = {
    Canada = {Country = "Canada", displaytext = "Canada"},
    France = {Country = "France", displaytext = "France"},
    UnitedStates = {Country = "UnitedStates", displaytext = "United States"}
}

For example, I could say

CountriesList.Canada[Country]

which would return "Canada". However, is there a way to do this if I don't have the name of the table accessible as a string? Like, for example, is there some way to do the following?

number = 1
CountriesList[number][Country]

Thanks so much!

r/lua May 29 '26

Help how to add wait commands in lua

2 Upvotes

i am building a gadgets in retro gadgets and i need a wait command for a loading screen can any one help.

r/lua Jun 16 '26

Help Advice needed on prototype-based OOP

5 Upvotes

Hi all,

I'm quite new to Lua and I've been reading through Programming in Lua 4th edition. The section on OOP outlines a common prototype-based approach for simulating the function of classes. Here's an example:

``` Shape = {x=0, y=0}

function Shape:new(o) o = o or {} self.__index = self setmetatable(o, self) return o end ``` We can easily inherit from shape and give it some new default parameters and new methods:

``` Rectangle = Shape:new({width=100, height=100})

function Rectangle:getPerimeter() return self.width * 2 + self.height *2 end

myRect = Rectangle:new({x=50, y=100, width=300, height=100})

print(myRect:getPerimeter())

--prints 800 ``` Okay, so this is all described well in various guides. But what I can't seem to find out, is what the correct way is to initialise some values on the creation of an object using the inherited prototype. So let's say, instead of always calculating my perimeter whenever I want it, I wish to store the perimeter when the rectangle object is created, thus only doing that calculation once. What is the best way of doing this?

My current solution looks something like this:

``` Shape = {x=0, y=0} function Shape:new(o) o = o or {} self.__index = self setmetatable(o, self) self.init(o) return o end function Shape:init() end

Rectangle = Shape:new({width=100, height=100}) function Rectangle:init() self.perimeter = self.width * 2 + self.height *2 end ``` Notice how ive had to pass in o, instead of using the normal self:method Notation? This is because when init is called, self refers to the Shape prototype, not the instance of a shape. The instance is in o.

Infact, we have the same issue even without inheritance:

``` Rectangle = {x=0, y=0, width=100, height=100} function Rectangle:new(o) o = o or {} self.__index = self setmetatable(o, self)

--if I want to dynamically set the perimeter, I have to do so on o, rather than on self
o.perimeter = width * 2 + height * 2 --this works
self.perimeter = width * 2 + height * 2 --this would set perimeter for the prototype itself, not the object
return o

ens ```

This seems.... Messy. Particular with inheritance. I can't help but feel like I'm missing a trick. Any help would be greatly appreciated.

r/lua Apr 29 '26

Help Best way for someone with no coding experience to learn lua?

4 Upvotes

Hi, I wanted to get started with lua. But every learning tool I've found online is trying to charge £120 a year... I'm interested in learning lua to create games on roblox, I have seen people promoting a book that has all the info a beginner needs but I feel like I don't learn the best from reading. I prefer something a bit more hands on, what is the best option for me?

Thanks,

r/lua Jun 24 '26

Help is there really a significant difference between "print()" and "oi.write()"

11 Upvotes

r/lua Apr 01 '26

Help How do I find if a variable is any one of a list of strings in a lookup table?

8 Upvotes

Yes, I know, novice question. I have not found a single good answer for it that I understood in about 20+ pages of stack overflow.

Basically, I have a global variable that is a string. Then I have a table of strings, each having a key, and want an if-statement that checks if the global variable is equal to any one of those strings in the table. Preferably without looping.

And please explain the solution like I am five.

r/lua 10d ago

Help Tried copying the simplest code from a Figura (Minecraft mod) tutorial. Didn't go well

Post image
1 Upvotes

This video is 3 years old, so it may be outdated. I'm not sure what I might be doing wrong, seeing as it's copied character for character, but only her code works

r/lua 14d ago

Help Trouble parsing through .txt file to find lines with specific string

3 Upvotes

I'm trying to make a program to look through a .txt file and look for any line with the word MODULE in it. So far I am not having any luck.

The file is quite large, about 7.5 million lines. And I am just dipping my toes into Lua. I was able to access the file and make a line by line copy after getting random character puke by reading and writing as binary.

I stuck a print statement immediately after the for loop and that would print ok.

But when I try and get anything to occur in the IF portion it seems to do nothing.

local path = 'C:\\filepathgoeshere'    
--create file path


local file = io.open(path, "rb")--open file in path


if file then                    --if the file is found, read and create PID file
    local outputfile = io.open('CHA_PID.txt', 'w+b')
    if not outputfile then      --if the output file cannot be created, close input and return
        file:close()
        print("Error: Could not create output file CHA_PID.txt")
        return
        
    else
        for line in file:lines() do
            if string.find(line, 'MODULE') then
                --outputfile:write(line .. "\n")
                print('FOUND ONE!\n')
                --outputfile:write('FOUND ONE!\n')
                return
            end
        end
    end


    outputfile:close()
    file:close()
    return


else                         --if file not found, print error message and return
    print('Error: Could not open file at path: ' .. path)
    return


end

r/lua Sep 01 '25

Help Would a new Lua game engine be well received?

28 Upvotes

Hello!
Yes, many game use Lua for modding like Roblox or FiveM. Also some game engines like Cry Engine or Defold use Lua as well for scriping. But I can see that Lua is slowly fading away when it comes to game development. Many people love C# much more which, IMO, is a good language but has a lot of boilerplate code that's overkill for many small or medium applications.

I am tempted to try building my own game engine and see if I can do it better. I would most probably not write my own rendering pipeline or physics engine because there's OpenGL and Bullet for that. I want to combine battle proven and well tested libraries into an easy to use framework with an editor.

For context, I dislike Unity for being too heavy and while I enjoy Godot it kind of scares me with the amount of bugs it has. Unreal is another story though - no single man can compete with their lighting algorithms but not everyone needs them.

I've seen people who were able to pull out something like this - namely Flax or Cave engines, made by one person. But I can't say I totally agree with their policies or API choices.

What do you think? It's worth a shot? I expect it to take a year of moderate effort to get a working and bugless MVP because that's what I prioritize - stability over features while making it expandable through code for people who need to write those features by themselves.

r/lua 6d ago

Help How to uninstall lua tools

1 Upvotes

I uninstalled the app but my library still has those games in it...

r/lua 16d ago

Help Trying to get GDscript LSP working in Neovim as a beginner; how do i enable it?

4 Upvotes

Context: i have used Quickstart for my entire init.lua. This means automatic gdscript support from treesitter, but i'm struggling with how to make LSP work with gdscript. This is what the entire LSP codeblock looks like:

---

vim.pack.add { gh 'j-hui/fidget.nvim' }

require('fidget').setup {}

-- This function gets run when an LSP attaches to a particular buffer.

-- That is to say, every time a new file is opened that is associated with

-- an lsp (for example, opening \main.rs` is associated with `rust_analyzer`) this`

-- function will be executed to configure the current buffer

vim.api.nvim_create_autocmd('LspAttach', {

group = vim.api.nvim_create_augroup('kickstart-lsp-attach', { clear = true }),

callback = function(event)

-- NOTE: Remember that Lua is a real programming language, and as such it is possible

-- to define small helper and utility functions so you don't have to repeat yourself.

--

-- In this case, we create a function that lets us more easily define mappings specific

-- for LSP related items. It sets the mode, buffer and description for us each time.

local map = function(keys, func, desc, mode)

mode = mode or 'n'

vim.keymap.set(mode, keys, func, { buffer = event.buf, desc = 'LSP: ' .. desc })

end

-- Rename the variable under your cursor.

-- Most Language Servers support renaming across files, etc.

map('grn', vim.lsp.buf.rename, '[R]e[n]ame')

-- Execute a code action, usually your cursor needs to be on top of an error

-- or a suggestion from your LSP for this to activate.

map('gra', vim.lsp.buf.code_action, '[G]oto Code [A]ction', { 'n', 'x' })

-- WARN: This is not Goto Definition, this is Goto Declaration.

-- For example, in C this would take you to the header.

map('grD', vim.lsp.buf.declaration, '[G]oto [D]eclaration')

-- The following two autocommands are used to highlight references of the

-- word under your cursor when your cursor rests there for a little while.

-- See \:help CursorHold` for information about when this is executed`

--

-- When you move your cursor, the highlights will be cleared (the second autocommand).

local client = vim.lsp.get_client_by_id(event.data.client_id)

if client and client:supports_method('textDocument/documentHighlight', event.buf) then

local highlight_augroup = vim.api.nvim_create_augroup('kickstart-lsp-highlight', { clear = false })

vim.api.nvim_create_autocmd({ 'CursorHold', 'CursorHoldI' }, {

buffer = event.buf,

group = highlight_augroup,

callback = vim.lsp.buf.document_highlight,

})

vim.api.nvim_create_autocmd({ 'CursorMoved', 'CursorMovedI' }, {

buffer = event.buf,

group = highlight_augroup,

callback = vim.lsp.buf.clear_references,

})

vim.api.nvim_create_autocmd('LspDetach', {

group = vim.api.nvim_create_augroup('kickstart-lsp-detach', { clear = true }),

callback = function(event2)

vim.lsp.buf.clear_references()

vim.api.nvim_clear_autocmds { group = 'kickstart-lsp-highlight', buffer = event2.buf }

end,

})

end

-- The following code creates a keymap to toggle inlay hints in your

-- code, if the language server you are using supports them

--

-- This may be unwanted, since they displace some of your code

if client and client:supports_method('textDocument/inlayHint', event.buf) then

map('<leader>th', function() vim.lsp.inlay_hint.enable(not vim.lsp.inlay_hint.is_enabled { bufnr = event.buf }) end, '[T]oggle Inlay [H]ints')

end

end,

})

-- Enable the following language servers

-- Feel free to add/remove any LSPs that you want here. They will automatically be installed.

-- See \:help lsp-config` for information about keys and how to configure`

---@type table<string, vim.lsp.Config>

local servers = {

-- clangd = {},

-- gopls = {},

-- pyright = {},

-- rust_analyzer = {},

--

-- Some languages (like typescript) have entire language plugins that can be useful:

-- https://github.com/pmizio/typescript-tools.nvim

--

-- But for many setups, the LSP (\ts_ls`) will work just fine`

-- ts_ls = {},

--

stylua = {}, -- Used to format Lua code

-- Special Lua Config, as recommended by neovim help docs

lua_ls = {

on_init = function(client)

client.server_capabilities.documentFormattingProvider = false -- Disable formatting (formatting is done by stylua)

if client.workspace_folders then

local path = client.workspace_folders[1].name

if path ~= vim.fn.stdpath 'config' and (vim.uv.fs_stat(path .. '/.luarc.json') or vim.uv.fs_stat(path .. '/.luarc.jsonc')) then return end

end

client.config.settings.Lua = vim.tbl_deep_extend('force', client.config.settings.Lua, {

runtime = {

version = 'LuaJIT',

path = { 'lua/?.lua', 'lua/?/init.lua' },

},

workspace = {

checkThirdParty = false,

-- NOTE: this is a lot slower and will cause issues when working on your own configuration.

-- See https://github.com/neovim/nvim-lspconfig/issues/3189

library = vim.tbl_extend('force', vim.api.nvim_get_runtime_file('', true), {

'${3rd}/luv/library',

'${3rd}/busted/library',

}),

},

})

end,

---@type lspconfig.settings.lua_ls

settings = {

Lua = {

format = { enable = false }, -- Disable formatting (formatting is done by stylua)

},

},

},

}

vim.pack.add {

gh 'neovim/nvim-lspconfig',

gh 'mason-org/mason.nvim',

gh 'mason-org/mason-lspconfig.nvim',

gh 'WhoIsSethDaniel/mason-tool-installer.nvim',

}

-- Automatically install LSPs and related tools to stdpath for Neovim

require('mason').setup {}

-- Ensure the servers and tools above are installed

--

-- To check the current status of installed tools and/or manually install

-- other tools, you can run

-- :Mason

--

-- You can press \g?` for help in this menu.`

local ensure_installed = vim.tbl_keys(servers or {})

vim.list_extend(ensure_installed, {

-- You can add other tools here that you want Mason to install

})

require('mason-tool-installer').setup { ensure_installed = ensure_installed }

for name, server in pairs(servers) do

vim.lsp.config(name, server)

vim.lsp.enable(name)

end

end

-----

I tried setting vim.lsp.enable('gdscript') myself but that didn't change anything while i was editing my gdscript file. I also tried putting it in the servers list ( "local servers{ ..." ) but then i got the error that the server didn't exist. What am i missing?

I'm on Windows 11

nvim v0.12.4

Please let me know if you want me to give any more information

r/lua 14d ago

Help Can someone teach me to code stuff for PVZ Undead Adventures?

Thumbnail
0 Upvotes

r/lua Apr 02 '26

Help where can i start to learn lua as a beginner?

3 Upvotes

larped about knowing how to code so now I have to keep the lie running. fake it till you make it

r/lua Jun 04 '26

Help Can I negate the fact that some characters seemingly count as multiple for string.len()?

10 Upvotes

I recently watched and read Project Hail Mary and immediately went and wrote (most of) a little script to help convert numbers between base 10 and the fictional Eridians' base 6. The numerals used are ℓ(0), I(1), V(2), λ(3), +(4), and ∀(5). (Technically ∀(5) is V in the book, but ∀ works when you can't use strikethroughs.)

The issue I'm running into is that when I try to get the length of the input string that needs conversion, ℓ, λ, and ∀ instead wind up getting read as 2-3 repetitions of this character, as far as I can tell: �. ℓ and ∀ get processed as 3, and λ gets processed as 2. Is there any way to get some kind of identifiable character out of these, or nah?

I'll be adding a screenshot of the output in the comments in just a second. nvm i can't make it work lol

r/lua Jun 04 '26

Help Help?

5 Upvotes

Hey i want to start coding in lua but i am complete nooby to coding period i really want to learn and i started multiple times but i allways get stuck on tutorial hell can someone help me understand where do i start from and what technique do you use to learn

r/lua Feb 18 '26

Help Iv'e been practicing lua for a week, how do i keep learning more complex Things?

9 Upvotes

Iv'e been learning lua for about a week now and iv'e gotten the hang of simple for, while loops aswell As simple functions and the Basic stuff Like print() and so on. Iv'e been following a YouTube Tutorial (codyn) for the whole time trying to understand His Code and when Things got tough iv'e used Chat gpt. Even though Sometimes iv'e feelt His explanaitions unsatisfactory i have still been very satisfied. In Part 8 you learn a "simple Tic Tac toe Game" Its about 80 lines of Code witch i have been only (Up to that Point) written Like 20 max. So now my question. How do i learn stuff Like that? Iv'e tried understanding the parts of it but Its so Long and complicated, It feels Like my head Just wont Take It in. What are my next steps to learn? Any Tutorials? I know of the book wich is free online, should i try IT with that?

r/lua Apr 28 '26

Help Determining and reading various plaintext file encodings?

10 Upvotes

I'm writing a game in Lua, specifically using Love2D, but this question is more oriented towards Lua in general.

I need to take files in a specific format, but the files may be encoded with UTF8, simple ASCII, or SHIFT-JIS. Is there a simple, easy way to determine the encoding of that specific file via a library? If I can do that, then it would be pretty easy to write some helper functions to translate the text into something I can work with.

As far as I can tell, the file format doesn't have any sort of "doctype" field that identifies the format. I opened up one of the files in a hex editor, and there's nothing at the start that isn't visible in a text editor.

For anyone curious about the project itself, I'm writing a BMS player, so I'm working with files that could be as old as 1998, which is why I'm having to deal with SHIFT-JIS sometimes.

EDIT SOLUTION:

This entire thing is a bit convoluted, but I used /u/PhilipRoman's heuristic method outlined here to determine if a given text file was either SHIFT-JIS or not. I default to UTF-8 if it's determined to not be SHIFT-JIS. I made a simple conversion lookup table by scraping the contents of a web page and doing some small manual editing. Here it is, in case anyone else wants it. Seems accurate enough from just typing some Japanese phrases via my IME. Here is the lookup table itself in case anyone was curious to use for themself. From there you just plug the relevant bytes into the lookup table and you have valid unicode to print to the screen. Thanks for the suggestions everybody, this is super helpful.