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
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
Card and "self" don't have a nil value anymore and the 2nd line is yellow for some reason and ive been trying to fix it on my own forever now, code is in the link in the body text. (balatro)
https://redd.it/1n5jf9k
@r_lua
Would a new Lua game engine be well received?

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.

https://redd.it/1n5ye82
@r_lua
Chatgpt vs YouTube vs black box, which of these could help a person code faster and way better

So I wanna learn how to noscript Lua at a young age and as fast as possible, ik that YouTube is usually the most casual way but most of the tutorials are extremely boring and long and kinda bland

Using chatgpt on the otherhand, doing some bit of asking, I figure out that chatgpt sometimes gives a convincing wrong answer so Idk about this

I'm not tryna rush learning how to noscript, it's just YouTube is just boring and I have quite a low attention span on video. But if I have no choice then so be it

https://redd.it/1n6kvm3
@r_lua
is this the original programming in lua 2016 book or am i scammed
https://redd.it/1n6xg20
@r_lua
Where can you commission lua Devs?

Are there any sites that have a review/price system for commission work?

Looking for a talented Lua Dev to develop a semi advanced game add-on/plugin but have no idea where to look.

https://redd.it/1n7ei93
@r_lua
I'm looking for programmers for a Roblox Studio project.

This is a project made independently and made for the love of art.
To write code from the experience in LUA.

(Clarification: the group is in Spanish so this was written with Google Translate)

https://redd.it/1n7yewi
@r_lua
How do I detect specific text from input, and could you give suggestions on how to improve my code (I am making RPS)

rps = {'r', 'p' ,'s'}

local Playerpick = io.read()



local function plachoice()

if Playerpick == rps then

print(Playerpick)

else

print("Pick r, p or s")

end

end



local function comchoice()

return print(rps[math.random(#rps)\])

end



local function banner()

print("!!WELCOME TO ROCK PAPER SCISSORS!!")

print("!!WHEN READY, ENTER EITHER R, P OR S!! (LOWERCASE R, P OR S) ")

end



banner()

comchoice()

plachoice()

https://redd.it/1n8fwtw
@r_lua
How do i start noscripting on roblox

i've been searching up ways to learn luau and lua and i couldn't find anything if someone have some info please tell me ASAP



https://redd.it/1n8fspc
@r_lua
Project ideas for a 5-7/10 lua skill level user?

Hi! I'm bored and i want to code something in lua, but i don't have any ideas, so i want to hear you guys ideas for a lua project. Also im really sorry if i put a wrong flair, i was debating on help and project.

Thanks!

https://redd.it/1n9ybyr
@r_lua
How can I share my screen and turn on my camera with luamacros?

Is it possible to press a key and discord will share screen 1? From what ive seen It would need to use the gui witch wouldn't work for me.

https://redd.it/1na7l64
@r_lua
Typehint comments possible syntax

Hi Friends! Recently I told here about my meek attempt to make small "syntax sugar" additions to Lua source code and there was one curious comment suggesting that "type hints" on function arguments and return may be useful addition too.

While I have no skills to make such type-hints actually verify value types (in runtime?) of course it is easy to add them as a kind of special comment, e.g. so that programmer use them as reminder (and perhaps later some external tool for checking types could be devised) - I used colon to separate them (the typehint itself could be any identifier, except reserved words).

function hash(s:str):int
-- ...
end

As they are optional this is still compatible with original Lua and addition to the code is less than ten lines.

However I wonder - colon is used in Lua for different things (table-related case particularly) - seemingly this should never cause any semantic/syntactic "collision" but perhaps I'm wrong and missing something?

Project could be seen here: https://github.com/RodionGork/lua-plus/ (and could be tested online, by the way, if you follow the links to Lua-emcc - I decided to add these "amends" here).

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