Why this function always returns a table?

hi, I was working at a module to make guns easier but I want developers to can create they own functions, but always it returns a table. The module script (a part):


function GunData:CreateNewFunction(name,func)
	self[name] = func
end

how I use it:


local Shoot = Gun:CreateNewFunction('Shoot',function(input)
	print(input)
end)

Gun:Shoot('Thing')

it prints things like: table: 0x01572dfc7a9fdc5d

1 Like

Well do you want the table to be printed in a proper format? If so then you may want to have a look at this.


I’m also having a hard-time understanding what you’re trying to say.

3 Likes

i try to make a function that u can create Custom Functions to a Gun, but like in the example, the parameters (i don’t know why) transforms into random tables, any help?

1 Like

i tried this code and it worked:


local Shoot = Gun:CreateNewFunction('Shoot',function(_,thing)
	print(thing)
end)

Gun:Shoot('Thing')

1 Like

Your issue is that calling functions using colon syntax, table:func(), passes the original table to the function as the first argument.* If defined using colon syntax, function table:func() ... end, then the implicit self variable exists as you use it.

Edit: *that’s why adding the _ at the beginning fixes it here, obviously. Something like this is a bit of a code smell, whatever you’re trying to do might have a more sensible means of accomplishing the same task :wink:

2 Likes

i see that, i use this code and it works:


local Shoot = Gun:CreateNewFunction('Shoot',function(GunData,...)
	print(...)
end)

Gun:Shoot('lolloollo','thing','random')

but is there any way to remove the table added by : ?

You can call it with a dot instead:

local Shoot = Gun:CreateNewFunction('Shoot',function(...)
	print(...)
end)

Gun.Shoot('foo', 'bar')
2 Likes

I know that but I want to do it with : , any hacky way? with . works but with : i need to put a _

Yes, you could wrap it in another function that throws away the first parameter:

local function noSelf(f)
    return function(self, ...)
        return f(...)
    end
end

local Shoot = Gun:CreateNewFunction('Shoot', noSelf(function(...)
	print(...)
end))

Gun:Shoot('foo', 'bar')

The call to ‘noSelf’ can be included in your CreateNewFunction method so you don’t need to think about it at all.

2 Likes