This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
jay5476's profile picture

Code Not Working(Attempt To Index A Nil Value)

Started by jay5476, 02 September 2013 - 12:59 AM
jay5476 #1
Posted 02 September 2013 - 02:59 AM
hi guys, im wondering if it is possible to do something
in my button api
code can be found here: http://pastebin.com/WBGQ1PFa
I want to make it so the user does not have t set the metatable of there button to mainButton

edit: changed my question title now irrelevant
Edited on 02 September 2013 - 01:35 AM
Zudo #2
Posted 02 September 2013 - 04:06 AM
What line does it occur on?

e.g: program:52:attempt to index ? (a nil value)
jay5476 #3
Posted 02 September 2013 - 04:43 AM
it doesn't anymore I changed my question
edit: changed my question title now irrelevant
I also have solved this myself now
Yevano #4
Posted 02 September 2013 - 10:49 AM
I want to make it so the user does not have t set the metatable of there button to mainButton

You could make a function which creates a new class for you given your own constructor. Example usage of such a function:


local myButtonSubclass = class(mainButton, function(self, x, y, w, h)
	mainButton.init(self, x, x + w, y, y + h)
end)

It could be implemented as


function class(extend, constructor)
	local newClass = { }
	newClass.init = constructor
	setmetatable(newClass, extend)
	function newClass.new(self, ...)
		local self = setmetatable({ }, {__index = newClass})
		constructor(self, ...)
		return self
	end
	return newClass
end

I do something similar in my SEE runtime. You can of course implement this in different ways to suite your needs.
jay5476 #5
Posted 03 September 2013 - 05:20 AM
thanks for help anyways I might release this soon the soloution I found was to do this
in api:

function create(buttonTable)
return setmetatable(buttonTable,mainButton)
end
and in my test program

os.loadAPI("button")
theButtonIUse = {}
button.create(theButtonIUse)
it seems to work fine as long as buttonTable is a legitimate table
theoriginalbit #6
Posted 03 September 2013 - 05:51 AM
it seems to work fine as long as buttonTable is a legitimate table
Make it

function create( t )
  return setmetatable( type(t) == "table" and t or {}, mainButton )
end
that way if they supply a table it's used, or else a fresh table is returned