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
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
Trying to add 10 to hp value, no matter what said hp value is

I'm playing around with a game's code and I want to add an additional 10 hp to their regular hp at all times. As a test, this successfully makes their hp 20.

WriteShort (MaxHP, 10 + 10)

But I can't work out how to make it so they have an extra 10 hp, regardless of what their regular hp is. I thought it would be something like 'WriteShort (MaxHP + 10), but it isn't.

https://redd.it/1n4duw0
@r_lua
Cmake issues with lua

cmakeminimumrequired(VERSION 3.31.5)
set(CMAKECXXSTANDARD 23)
set(CMAKECXXSTANDARDREQUIRED ON)
project(PongTest)

include(cmake/CPM.cmake)
include
directories(include)

CPMAddPackage(
  NAME raylib
  GITHUBREPOSITORY raysan5/raylib
  GIT
TAG master
  OPTIONS "RAYLIBBUILDEXAMPLES OFF"
)

CPMAddPackage(
  NAME sol2
  GITHUBREPOSITORY ThePhD/sol2
  VERSION 3.3.0
)

CPMAddPackage(
  NAME lua
  GIT
REPOSITORY https://gitlab.com/codelibre/lua/lua-cmake
  GITTAG origin
)

add
executable(PongTest src/Main.cpp)

targetincludedirectories(PongTest PRIVATE ${luaSOURCEDIR}/src  ${luaINCLUDEDIRS} ${luaBINARYDIR}/src)
targetlinklibraries(${PROJECTNAME} PRIVATE "-lstdc++exp" ${luaLIBRARIES} lua raylib sol2)




I'm using cmake w cpm to build my lua, as shown above
but i keep getting these errors:



build] C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/14.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -llua: No such file or directory
[build] collect2.exe: error: ld returned 1 exit status
[build] CMakeFiles\PongTest.dir\build.make:102: recipe for target 'PongTest.exe' failed
[build] mingw32-make.exe[3]: *** [PongTest.exe] Error 1
[build] CMakeFiles\Makefile2:332: recipe for target 'CMakeFiles/PongTest.dir/all' failed
[build] mingw32-make.exe[2]: *** [CMakeFiles/PongTest.dir/all] Error 2
[build] CMakeFiles\Makefile2:339: recipe for target 'CMakeFiles/PongTest.dir/rule' failed
[build] mingw32-make.exe[1]: *** [CMakeFiles/PongTest.dir/rule] Error 2
[build] Makefile:196: recipe for target 'PongTest' failed
[build] mingw32-make.exe: *** [PongTest] Error

not sure why it cant find -llua, if i remove all the target include directories, and replace ${lua_libraries} with just lua, it cant find <lua.h> why? It builds but still gives these errors

https://redd.it/1n4f0e0
@r_lua
i need help

currently making swep for gmod, but lua keeps whining about "eof near end" and "argument near ="
i had checked it twice, thrice, quadrice, and yet i dont understand where actually i had missplaced it...im kind of new at coding, so my code might look horrific, ill appreciate at least being told where i need to put ends and where i'll need to remove them!
function SWEP:DrawWorldModel(flags)

self:DrawModel(flags)

end



SWEP.SetHoldType = "melee2"

SWEP.Weight = 5

SWEP.AutoSwitchTo = true

SWEP.AutoSwitchFrom = false



SWEP.Slot = 1

SWEP.SlotPos = 4

SWEP.DrawAmmo = false

SWEP.DrawCrosshair = false



SWEP.Spawnable = true

SWEP.AdminSpawnable = true

SWEP.AdminOnly = false



SWEP.Primary.ClipSize = -1

SWEP.Primary.DefaultClip = -1

SWEP.Primary.Ammo = "none"

SWEP.Primary.Automatic = false



SWEP.Secondary.ClipSize = -1

SWEP.Secondary.DefaultClip = -1

SWEP.Secondary.Ammo = "none"

SWEP.Secondary.Automatic = false



SWEP.ShouldDropOnDie = true

local SwingSound = Sound("LambdaWeapons/sounds/wpn_golf_club_swing_miss1")

local HitSound = Sound("LambdaWeapons/sounds/wpn_golf_club_melee_01")



SWEP.HitDistance = 49

function SWEP:Initialize()

self:SetWeaponHoldType( "melee2" )

end



function SWEP:PrimaryAttack()

if (CLIENT) then return

end

local ply = self:GetOwner()

ply:LagCompensation(true)



local shootpos = ply:GetShootPos()

local endshootpos = shootpos + ply:GetAimVector() * 75

local tmin = Vector( 1, 1, 1 ) * -10

local tmax = Vector( 1, 1, 1 ) * 10



local tr = util.TraceHull( {

start = shootpos,

endpos = endshootpos,

filter = ply,

mask = MASK_SHOT_HULL,

mins = tmin,

maxs = tmax } )



if not IsValid(tr.Entity) then

tr = util.TraceLine ( {

start = shootpos,

endpos = endshootpos,

filter = ply,

mask = MASK_SHOT_HULL } )

end





local ent = tr.Entity

if(IsValid(ent) && (ent:IsPlayer() || ent:IsNPC() ) ) then



self.Weapon:SendWeaponAnim(ACT_VM_HITCENTER)

ply:SetAnimation(PLAYER_ATTACK1)



function SWEP:DealDamage()

local anim = self:GetSequenceName(self.Owner:GetViewModel():GetSequence())



self.Owner:LagCompensation( true )



local tr = util.TraceLine( {

start = self.Owner:GetShootPos(),

endpos = self.Owner:GetShootPos() + self.Owner:GetAimVector() * self.HitDistance,

filter = self.Owner,

mask = MASK_SHOT_HULL

} )

end

if ( !IsValid( tr.Entity ) ) then

tr = util.TraceHull( {

start = self.Owner:GetShootPos(),

endpos = self.Owner:GetShootPos() + self.Owner:GetAimVector() * self.HitDistance,

filter = self.Owner,

mins = Vector( -10, -10, -8 ),

maxs = Vector( 10, 10, 8 ),

mask = MASK_SHOT_HULL

} )

end





ply:EmitSound(HitSound)

ent:SetHealth(ent:Health() - 140)

ent:TakeDamage(140, ply, ply)

if(ent:Health() <=0) then

if (damage >= DMG_BULB) then

ent:Kill()

end



ply:SetHealth( math.Clamp(ply:Health() +0, 1, ply:GetMaxHealth() ) )

elseif( !IsValid(ent) ) then

self.Weapon:SendWeaponAnim(ACT_VM_MISSCENTER)

ply:SetAnimation(PLAYER_ATTACK1)

ply:EmitSound(SwingSound)



end



self:SetNextPrimaryFire(CurTime() + self:SequenceDuration() + 0.1)





ply:LagCompensation(false)

end



function SWEP:CanSecondaryAttack()

return false end

https://redd.it/1n4wopr
@r_lua
People who do lua for living, what is your job and what industry are you in?

I'm curious how you can earn money with lua besides modding/game dev :)


https://redd.it/1n54gzb
@r_lua
How do do OOP in Lua 5.1 C API?

I am new to Lua here. I am using Lua 5.1 C API and trying to create a bunch of OOP like interface for Point, Box, Panel, etc. such that,

pt = Point(10, 20)

and

pt = Point.new(10, 20)

are the same. I want to do all this in C because I have a bunch of objects backed by user-data that I'd like to register in Lua.

My Lua code looks like this:

pt = Point(10, 20)
print(pt)

But print prints nothing even though the __tostring meta function exists. My gdb isn't even hitting l_pt_stringify. Interestingly, l_pt_delete for GC does get called. I've pasted relevant source code below.

What am I doing wrong?

Thing is I want to create some kind of api registration function that takes both class name, interface and meta methods and registers then in a consistent fashion so I don't have to fiddle around with Lua for every class.

So far, this is the C code I have. Removed unnecessary stuff.

#define CNAME "Point"

static int
l
ptnew(luaState L)
{
int nargs = 0;
struct ui_point
result = NULL;
int x = 0, y = 0;

nargs = luagettop(L);
if (nargs == 1 && lua
type(L, 1) == LUANUMBER && luatype(L, 2) == LUANUMBER) {
x = lua
tonumber(L, 1);
y = luatonumber(L, 2);
} else {
lua
error(L);
}
result = ptallocate(x, y);

if (result != NULL) {
struct ui
point rtmp = NULL;

rtmp = (struct uipoint **)luanewuserdata(L, sizeof(struct uipoint **));
*rtmp = result;
luaL
getmetatable(L, CNAME);
lua
setmetatable(L, -2);
} else {
luaerror(L);
}
return 1;
}

static int
l
ptdelete(luaState L)
{
int nargs = 0;
struct ui_point
self = NULL;

nargs = luagettop(L);
self = *(struct ui
point )luaLcheckudata(L, 1, CNAME);
if (nargs == 1) {
}
ptfree(self);
return 0;
}

static int
l
ptcall(luaState L)
{
lua_remove(L, 1);
return l_pt_new(L);
}

static const luaL_Reg m_funcs[] = {
{ "__gc", l_pt_delete },
{ "__lt", l_pt_lt },
{ "__le", l_pt_le },
{ "__eq", l_pt_eq },
{ "__tostring", l_pt_stringify },
{ NULL, NULL },
};

static const luaL_Reg i_funcs[] = {
{ "new", l_pt_new },
{ "getx", l_pt_getx },
{ "gety", l_pt_gety },
{ NULL, NULL },
};

void
lua_point_register(lua_State
L)
{
luaLopenlib(L, CNAME, ifuncs, 0);
luaL
newmetatable(L, CNAME);
luaL
openlib(L, 0, mfuncs, 0);
lua
pushliteral(L, "index");
luapushvalue(L, -3);
lua
rawset(L, -3);
luapushliteral(L, "metatable");
lua
pushvalue(L, -3);
luarawset(L, -3);
lua
pop(L, 1);
luanewtable(L);
lua
pushcfunction(L, lptcall);
luasetfield(L, -2, "call");
lua
setmetatable(L, -2);
luapop(L, 1);
lua
pop(L, 1); / Is this necessary? /
}


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