Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

How create a new object with different values

janac

New Coder
I'm new to Lua, but not to coding. Most of my coding has been in C++. I really confused about the syntax around creating and instantiating objects. The code below is working, but how do I create a new object with a different table and a different x and y?

Code:
pad={
x=63,
y=63,
w=9,
h=1,
clr=143,
pad_pxl={{-4,0},{-3,0},{-2,0},{-1,0},{0,0},{1,0},{2,0},{3,0},{4,0}},
state=0,
stbl={-3,-2,-1,0,1,2,3},
rtm=time(),
rst=true,
ptm=0,
dla=1,
new=function(self,tbl)
tbl=tbl or {}
setmetatable(tbl,{
__index=self
})
return tbl
end,
update=function(self)
--etc.
,
draw=function(self)
--etc.
end
}
 
Welcome to Lua! The syntax for creating and instantiating objects can feel a bit different coming from C++, but you’re already pretty close with your setup.

In Lua, your pad table acts as a sort of "class" or prototype. The new function you wrote is designed to create a new instance based on this prototype. To create a new pad object with different values for x and y, you just need to pass a table with those values when you call pad:new().

Here's how you can do it:

Code:
-- Create a new pad object with different x and y values
local new_pad = pad:new({x=100, y=200})

-- Now new_pad.x is 100, and new_pad.y is 200

This will create a new table (new_pad) that inherits from pad but has x=100 and y=200 specifically set for this instance.

Let me know if you have more questions on Lua – happy to help!
 

New Threads

Buy us a coffee!

Back
Top Bottom