Lua - Reddit – Telegram
Lua - Reddit
30 subscribers
278 photos
31 videos
4.23K links
News and discussion for the Lua programming language.

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

Powered by : @r_channels & @reddit2telegram
Download Telegram
setmetatable and index

I'm doing more on classes - and I'm making a class


MyClass = {}
function MyClass:new()
o = {}

setmetatable(o, MyClass)
self.index = MyClass


return o
end

function MyClass:myfunc()
print("myfunc called")
end


c = MyClass:new()

I realise the manual example uses 'self' rather than MyClass - but I'm not looking for inheritance yet.

And I'm wondering why I need both to set the metatable and index to MyClass. Just setting the metatable fills the metatable of c with fields named after the MyClass functions (eg myfunc) that point to the metamethods - so they should be callable? Yet calling them is calling nil. Why do I require index to be set as well?
I've read the manual on the index metamethod and I see how setting index to the MyClass table and the index metamethod is called if there is no field in the metatable - yet the metatable of c has the field myfunc in even if I miss setting index.

https://redd.it/1mt5726
@r_lua
How to install a package in luajit?

I have tried to install packages in luajit using luarocks but it fails due to luajit’s maximum 65536 constants limitation.

1. Is there a way to install packages in luajit using luarocks?
2. What are other available alternatives?

https://redd.it/1mtl20b
@r_lua
Looking for FiveM developers

We are seeking a developer to assist our lead developer. Responsibilities will include everything from small fixes to adding new functionalities and features to our existing codebase.

We use a custom framework based on the Mythic framework. While the ability to build complete noscripts is not required, it is a plus. Experience with React and UI development is also beneficial.

Please note that we are not able to pay at this time; however, you will gain valuable experience and a meaningful journey in development. If you're new to FiveM and eager to learn, feel free to reach out.

DM > brains1960
In-discord



https://redd.it/1mtvbe6
@r_lua
where can i learn lua?

Im a 2nd year electrical engineer students, ive already learned c++ due to this (im no new to programming)

https://redd.it/1mus5we
@r_lua
can someone make me a cs2 no recoil noscript for all the guns with a simple toggle feature



https://redd.it/1mva4ty
@r_lua
Save system in Roblox Studio

Hi everyone,

I'm currently developing a multiplayer tycoon-style game in Roblox Studio where players manage animal mutant merger plots where they can build pens, hatch eggs, and merge animals.

Here’s the core design:

\- There are 5 unique plots in the world.

\- Players can scroll through and claim a plot they like.

\- Once claimed, they can build, place items, and interact with the world only within their plot boundaries.

\- There’s a central area with NPC shops where players can buy/sell items using an in-game currency.

What I Need Help With:

I’m trying to build a save system that:

\- Persists player progress across sessions (plot ownership, structures, inventory, currency, etc.)

\- Restores placed items on their plot when they rejoin and claim it

\- Supports respawning without losing plot ownership

\- Enforces build restrictions so players can only build inside their own plots

\- Is scalable, so I can add new features (animals, currency types, items) in the future without rewriting everything

I’m still very new to noscripting, so obviously I have been using GPT but have arrived at a dead end, what's the best way to go about this?

https://redd.it/1mvcjri
@r_lua
First time defining parameters of a custom function to create hexagon grid in TIC-80

So I want to make a civ-like game (eventually).

Today I decided to try and make just a grid and it was more complicated than I thought it would be.

First, I had to refresh my geometry knowledge. I confused hexagon with octagon, which was silly. But then I assumed diagonal lines are tilted at 45 degrees leading to me making very ugly hexagons. I went searching what angles do regular hexagons have and just to make sure, I double checked 30-60-90 triangle rules lol

So this is the final product and exactly what I was planning to achieve.

In the code I started with defining all points of the first hexagon and putting them into a list. I picked the length of each side equal to 8, starting with the top left diagonal line.
If you cut the upper part of a hexagon off, you'll get a triangle with 30-30-120 angles. You can then divide that triangle into two 30-60-90 triangles and calculate the distance between points as shorter sides of those triangles.

One is twice as short as hypotenuse. (8/2=4 which is the value of y1)

For the other I just used Pythagorean theorem.

Figuring out shift values was the most painful process and ngl a lot of it was guessing and intuition.

To actually draw a hexagon I used "for" loop of "line" function and added parameters to shift coordinates.

Then I created function to execute previous function in a loop while shifting it's x coordinates to create a row.

I added the same function, but with half of the x shift and full y shift. Hexagons aren't squares and can't just be stacked right on top of each other, but in between. Now it creates pair of rows which can be stacked without an x shift.

And finally... I just stack em.

I know it's not the clearest code, but it's 3am and I'm just happy it actually works despite me never setting parameters for a function before.

https://redd.it/1mvsv5n
@r_lua
Sentry SDK for Lua

This week is hackweek at Sentry (crash reporting service) and I wanted to try building an SDK for Lua:


https://github.com/getsentry/sentry-lua


The idea was to get a core set of Lua libraries (written in Teal) that are platform agnostic (aka: can run on standard Lua, LuaJIT, sandboxed in Roblox, etc) and then a set of platform specific libraries that could be used to have the SDK work on those platforms. For example, sending network requests.


It's very early days, but I got some CI that runs tests on Mac and Linux on different versions of Lua and LuaJIT. Some examples, including LÖVE (love2d framework) and Roblox. And I got it working on Xbox a minute ago but it's too duck taped to push so far, but I'll try to push this if not on the public repo, on a sentry-xbox private repo we can send invites to if folks want access.

https://redd.it/1mwnw38
@r_lua
LPEG and luajit: Lua is Awesome

This post may not be constructive or interesting, but I need to share my enthusiasm.

I started writing a VM entirely in Lua for my Plume language.

The idea was that "the VM will be horribly slow (inevitably, since it's an interpreted language running an interpreted language), but it's a prototype that can be ported to C later."

For parsing, instead of my "clean and serious" code, I thought, “Well, LPEG seems pretty solid, I'll do something quick and dirty just to get the AST out in one pass.”

In short, "quick and dirty" for prototyping. How wrong I was!

LPEG is monstrous. Very demanding in terms of abstraction, but once you understand the principle, it allows you to parse complex grammars with ease.

But parsing isn't everything: you can arbitrarily modify the capture flow in a simple and transparent way.

In the end, my "quick and dirty" code was shorter, more efficient, and easier to read than the old "clean code".

As for performance... Remember, a VM written in Lua isn't going to be lightning fast, right?

Well, thanks to the black magic of luajit, on the few benchmarks I wrote, Plume outperformed Lua 5.1 by 30%. Yes, on a 1-week dirty VM.



Lua is awesome.

https://redd.it/1my4byk
@r_lua
From a stupid old man ready to scream in anguish, aka a summer ruined by Microsoft

Apologies in advance for the novel.

Background.

I spent my summer taking a break from Fortnite after Chapter 6 season 3. I ended up trying a game in my Epic Library, Kingdom Come Deliverance - 2018, not KCD 2. It is a great game. The mod bug bit me. It always does.

Long story short, I started modding, using Basic Notepad++ and luanoscript from github
[https://github.com/dail8859/LuaScript](https://github.com/dail8859/LuaScript)

I am rather simple. On unix I grew up on pico and then nano on later BSD versions (dont get me started on how much I hate Vi/Vim. It worked, so I didnt bother with anything. I know a bunch of languages, but not xml or lua, so I learned slow, I learn through failure, needless to say I learned a LOT. By early July I got done what I wanted modding wise - I mod through the Nexus. I had set 4 goals when I started. 3 were done. The last, final and most difficult was making the physics engine actually a physics engine, and ripping out the IK - Inverse Kinetic Animation system, I had quit it 3 different times since late May when I started, honestly I thought it was a fools errand.

But I hate to lose, quit or otherwise fail, so like a fool I kept at it. Eventually I did actually start seeing ragdolls and other forms of actual physics in play. My goal was to have it done by now. Classes started last Monday - I am a Linguistics major, even though I know like 8 languages now.

Now, as they say, it is always darkest before the dawn, and I was almost done. Murphy has laws about that

8.13.25 hit like a fucking freight train. I actually didn't install the update for a couple of days, until 8.17.25

Microsoft update nuked me.

Everything stopped functioning properly I pretty much pulled my hair out in frustration

In what little time I have had this week, I actually worked with an AI, and lemme say I hate AI. I figure if I cant do something myself I shouldn't do it. But, I gotta say that JDroid, that is a cool little fella. Lemme say I am also not one for asking for help, but, pride is a bitch and I know when to get rid of it when applicable. Now, we worked out a semi-tenable solution, and learned what happened, though it took me a couple days to figure that out.

We ended up creating a virtual environment, system, network, etc. And it mostly worked, mostly. except for basicactor.lua which I have turned into my main file and it has grown a LOT since I have had to reverse engineer the entire physics, hit reaction, recoil, combat and death system in order to do all of this. But now, as soon as I touch it, it breaks.

CryEngine uses its own self contained lua environment and mini network for its client and server system. Since it is originally a single player system, made to run as a multiplayer environment. KCD runs on simple local server and the game client actually runs through that. Previously locals were called as such. It was simple, easy, it was easy, i didnt need a doctorate in programming to get that far, did I mention all my learning has been pretty much self taught since the late 80s? yea. I dont claim to be good, but I can work my way around gdb and a compiler really easy. turbo Pascal, c/c++/objc/java/javanoscript

luanoscript has a basic execute program to show errors. that was enough for me

require("Scripts/BasicAI.lua")

require("Scripts/BasicAITable.lua")

require("Scripts/AITerritory.lua")

require("Scripts/AIActions.lua")

require("Scripts/Anchor.lua")

require("SCRIPTS/Player")

require("SCRIPTS/BasicEntity")

require("SCRIPTS/CharacterAttachHelper")

end)

`if not success then`

`print("Failed to load dependencies: " .. tostring(error))`

`end`

`end`

`LoadDependencies()`

`local required = {`

`"System",`

`"AI",`

`"CryAction"`

`}`

`-- Debug version to test in different environments`

`local function DebugEnvironment()`

`print("Lua Version: " .. _VERSION)`

`print("Script global exists: " .. tostring(_G.Script ~=
nil))`

`print("Environment: " .. (package and package.config and "Standalone Lua" or "CryEngine Lua"))`

`end`

`-- Add missing mergef function`

`function mergef(dst, src, recurse)`

`if type(dst) ~= "table" or type(src) ~= "table" then return end`

`for k, v in pairs(src) do`

`if type(v) == "table" and recurse then`

`if type(dst[k]) ~= "table" then dst[k] = {} end`

`mergef(dst[k], v, recurse)`

`else`

`dst[k] = v`

`end`

`end`

`return dst`

`end`

`function table.copy(t)`

`local u = { }`

`for k, v in pairs(t) do`

`u[k] = type(v) == "table" and table.copy(v) or v`

`end`

`return setmetatable(u, getmetatable(t))`

`end`

`-- Safe initialization that works in all environments`

`local function SafeInitialize()`

`-- Only initialize if we're not in CryEngine`

`if not _G.Script then`

`_G.Script = {`

`ReloadScript = function(path)`

`print("Mock reloading: " .. path)`

`return true`

`end,`

`LoadScript = function(path)`

`return true`

`end,`

`UnloadScript = function(path)`

`return true`

`end`

`}`

`end`

`if not _G.Net then`

`_G.Net = {`

`Expose = function(params)`

`print("Mock Net.Expose called with: ")`

`print(" - Class: " .. tostring(params.Class))`

`print(" - ClientMethods: " .. tostring(params.ClientMethods ~= nil))`

`print(" - ServerMethods: " .. tostring(params.ServerMethods ~= nil))`

`return true`

`end`

`}`

`end`

`-- Add other required globals`

`if not _G.g_SignalData then`

`_G.g_SignalData = {}`

`end`

`-- Add basic System functions if needed`

`if not _G.System then`

`_G.System = {`

`Log = function(msg)`

`print("[System] " .. msg)`

`end`

`}`

`end`

`end`

`-- Validate environment`

`local function ValidateEnvironment()`

`print("\nEnvironment Validation: ")`

`print(" - UnloadScript: " .. tostring(type(Script.UnloadScript) == "function"))`

`print(" - Script: " .. tostring(Script ~= nil))`

`print(" - LoadScript: " .. tostring(type(Script.LoadScript) == "function"))`

`print(" - ReloadScript: " .. tostring(type(Script.ReloadScript) == "function"))`

`end`

`-- Run debug and initialization`

`DebugEnvironment()`

`SafeInitialize()`

`ValidateEnvironment()`

`-- Player definition with state validation`

`BasicActor = {`

`counter = 0,`

`type = "BasicActor",`

`SignalData = {},`

`WorldTimePausedReasons = {},`

`ValidateState = function(self)`

`print("\nBasicActor State: ")`

`print(" - Counter: " .. tostring(self.counter))`

`print(" - Type: " .. tostring(self.type))`

`end`

`}`

`-- Add this near the top of BasicActor.lua with the other core functions`

`function BasicActor:Expose()`

`Net.Expose{`

`Class = self,`

`ClientMethods = {`

`ClAIEnable = { RELIABLE_ORDERED, PRE_ATTACH },`

`ClAIDisable = { RELIABLE_ORDERED, PRE_ATTACH }`

`},`

`ServerMethods = {`

`-- Add any server methods here`

`},`

`ServerProperties = {`

`-- Add any server properties here`

`}`

`}`

`end`

`-- Initialize Player`

`BasicActor:ValidateState()`

`print("BasicActor successfully initialized")`

`-- Final environment check`

`print("\nFinal Environment Check: ")`

`ValidateEnvironment()` `require("Scripts/BasicAI.lua")`

Original local use.
Script.ReloadScript( "SCRIPTS/Player.lua");
Script.ReloadScript( "SCRIPTS/BasicEntity.lua");
Script.ReloadScript( "SCRIPTS/CharacterAttachHelper.lua")

How did I get nuked? Well. The last security update tossed a luaapi.dll into system32.dll

This shattered the self contained Cryengine lua local like a hammer and crystal. It also made luanoscript fairly useless. Luanoscript also utilizes lua 5.3 Now, you probably know where this is going right now.

File:951: attempt to index a nil value (global 'BasicEntity') any type of local dependency is gone, as luaapi.dll turns the entire system upside down. Now, using what is below I can get everything else to function, but if I even touch basicactor.lua it breaks, it is currently broken again and I am pulling my hair out.

In a nutshell, I want my global environment or my self contained lua noscript extension to function. I tried vs code. I am not making heads of tails of it and I do not have all summer
now to learn a new system. I just want this done so I can focus on my classes and move on from this.

Uninstalling the update does not yield any results, on a reboot it will just reinstall it.

I am at my wits end here

\-- Original

\-- CryEngine's Lua Environment
\-- Controlled, embedded Lua interpreter
\-- Direct access to engine functions
\-- All noscripts running in the same context
\-- Direct access to game globals

\-- After Windows Update: on 8.13.25

\-- Split Environment
\-- Standalone Lua interpreter (from Windows)
\-- Separate from CryEngine's Lua
\-- No direct engine access
\-- Missing game globals
\-- Different noscript loading paths

Unregistering and deleting luaapil.dll did nothing so I am at a loss.

Here is the basic use of this in pretty much any file which has a local dependency. As noted this works for pretty much everything, except the one file I depend on. I was only a day or two from being done. I also have no clue how any of the added code will function as a mod being added to other peoples games. For all I know Nexus could flag it bad content

local function LoadDependencies()

local success, error = pcall(function()

\-- Load in correct order

From here it is the normal actor data and parameters followed by all the functions
This is simply too much. I have been out of my depth of programming all summer using lua, cryengine and ripping apart the entire engine and putting it back together.

I would just like to go back and finish in my nice, simple fashion. I don't want to learn new stuff (I mean I do, but time is not on my side currently, so new stuff is not conducive to my college time).

So this is a "help me Obi-won Kenobi" moment.

Feel free to laugh :)

Thank you for reading

\~Diaz Dizaazter

https://redd.it/1my5xp2
@r_lua
Trying to edit LUA of a UASSET file in Unreal Engine

I am trying to delete a block of code from a LUA noscript that's in an abandoned mod for Oblivion Remastered. It's causing a UI bug that results in the game crashing or locking up keyboard commands so you have to force close it. It's just for personal use I don't plan on uploading to Nexus or whatever.

I've unpacked the files (*.uasset), I looked at what I need to edit in FModel, I downloaded Epic Launcher / Unreal Engine and launched it, I downloaded the github version of LuaMachine. And that's about it, I have no idea what to do from here to get this thing open so I can delete what I need to then I can go repack it and use it finally.

https://redd.it/1my88m6
@r_lua
Transitioned from Luau to Lua, any feedback or tips?

This is a varargs function, I just felt like messing around with it and I personally like how the syntax is compared to Luau

--- Lua 5.4.8
local function multiply(...)
    local vals = {...}
    for i, value in pairs(vals) do
        assert(type(value) == "number", ("invalid parameter #%d to multiply(); number expected, got %s"):format(i, type(value)));
    end
    local n = 1;
    for _, value in pairs(vals) do
        n = n * value;
    end
    return n;
end

local OK, res = pcall(multiply, 5, 1, 7, 2, 8, 1);
print(OK, res);

https://redd.it/1mylwdu
@r_lua
Is there way to perform calculations on GPU ?

I recently watch video "Simulating Black Hole using C++" and near the end of the video author started to use .comp files to perform movement calculations of rays. I know that you can use .glsl and .vert with love2d, but those are for displaying graphics. So my question is can you use Lua with GPU for calculation purpose ?

https://redd.it/1mz5tob
@r_lua
Just downloaded Lua, but...

There isn't a file to open it or anything. I downloaded 5.4 or .8 or something. Went into the files, but there isn't an application to run, so what am I meant to do with this? Thanks in advance.

https://redd.it/1mzwjb2
@r_lua
Add lua lib in CMake project

Hello. I've started learning the C API, but I can't get my first project to run because I don't know how to add the library to my project (I'm really bad at CMake).

I'm using Windows 11, VSCode, and MSYS2 UCRT64. I tried downloading the compiled Win64_mingw6 library version and added the following lines to my CMakeLists.txt file:

targetincludedirectories(test-bg PRIVATE
${CMAKESOURCEDIR}/liblua35/include
)
targetlinklibraries(test-bg PRIVATE
${CMAKESOURCEDIR}/liblua35/liblua53.a
)

But it didn't work. Honestly, I don't really know what I'm doing, so I would appreciate any help.

https://redd.it/1mzykui
@r_lua
Minor syntax amends in Lua - not-equals and compound assignments

Hi Friends!

As I utilized Lua for problems/puzzles website (e.g. to give users tasks of writing the code parts for game-like animations), I got some feedback from them, feelings that I share to some extent :) particularly they complained:

\- why not-equals is written with "\~=" rather than "!="

\- why there are no compound assignments

Later I noticed similar questions in "lua-l" mailing list, and as concerning "not equals" the main motivation (explained by Roberto himself) was, well, like he felt it is "more natural".

I tried to clone lua code and see whether I can make small code amendments to create additional version of "not equals" (so that both != and \~= could be used) - this was just 3 lines of code, all right (including single ! as alias for "not").

However with compound assignments it is more tricky. I succeeded in making it work for simple variables, everything from += to ..= for concatenation. For variables like table elements it however requires getting "more involved". So I'm slowly digging into this direction. Obviously compound assignments are not here for simple reason of how lexer/parser is implemented (especially its behavior of immediately generating opcodes).

So I wanted to ask - if you have seen (quite probably) other similar attempts, could you please point at them - I'll gladly have a look.

https://redd.it/1n0kgej
@r_lua
Can't print UTR-8 digits

[output](https://preview.redd.it/ekcrreq77flf1.png?width=516&format=png&auto=webp&s=c387fad7f7fde2318f2514e495b0ddb9865d99aa)

I'm trying to make a program that takes a .txt file and prints ever single letter, one line for each.
However, there are 2 empty spaces where the UTF-8 letters are supossed to be.
I thought this was a console configuration issue, but, as you can see in my screenshot, text itself is being sent and there's nothing wrong with it
Code:

local arquivoE = io.open("TextoTeste.txt","r")
local Texto = arquivoE:read("*a")
arquivoE:close()
print(Texto)

for letra in Texto:gmatch("[%aáàâãéèêíìîóòôõúùûçñÁÀÂÃÉÈÊÍÌÎÓÒÔÕÚÙÛÇÑ]") do
print(letra)
end

I tried using io.write with "\\n", but it still didn't display properly.


Contents of the TXT file:

Nessas esquinas não existem heróis
não




https://redd.it/1n0wgrb
@r_lua
Lua syntax minor amends - need help in testing

Hi Friends! Yesterday I told about my "exercise" of slightly amending Lua parser so that it will work, particularly, with compound assignments. Today I found a way (hopefully) to make it work for any complex expressions for L-values. And would be glad if you can spare 10-15 minutes to test it and perhaps invent some whimsical expressions to break it.

I don't mean this is ingenious amend which should be merged to official Lua of course :) it is more like exercise for me to study the source code of Lua.

Here is the repo: https://github.com/rodiongork/lua-plus \- it could be seen that change is really small (110 lines, half of them in readme) - in the latest commit.

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