Adding methods to an object

Posted by Blainer on Sat 13 Jun 2009 02:19 AM — 5 posts, 23,184 views.

#0
If I have:

	assert (package.loadlib("sqlite3.dll","luaopen_luasql_sqlite3")) ()
	aard_db = assert(sqlite3.open_memory("aard"))

And I want to add:

	function aard_db:test(arg)
		self.nrows(arg)
		return something
	end

So I can do this:

	aard_db:test("something")


How do I do it? Can I create a class called aard_db and add the methods from sqlite3.dll?



Amended on Sat 13 Jun 2009 03:04 AM by Blainer
Australia Forum Administrator #1
It's not going to be too easy. The variable aard_db is a userdata, not a table, and thus you can't add more things to it. A userdata is just a 4-byte pointer to an internal structure used by the database routines.

The userdata aard_db already has a metatable as well, so you can't just add one. I experimented with something like this:


mt = getmetatable (aard_db)


mt.__index.test = function (arg)
  print "in test"
  return self.nrows (arg)
end -- function


This indeed lets you add "test" as a function for the metatable in aard_db, however it doesn't know the self variable. Maybe you can get something along those lines to work, I'm not sure.
Germany #2
just use this code:
mt.__index.test = function (self, arg)
  print "in test"
  return self.nrows (arg)
end -- function

or this:
function mt.__index:test(arg)
  print "in test"
  return self.nrows (arg)
end -- function
Australia Forum Administrator #3
That gave this error:


Run-time error
World: smaug
Immediate execution
[string "Immediate"]:9: bad argument #1 to 'nrows' (:sqlite3 expected, got string)
stack traceback:
        [C]: in function 'nrows'
        [string "Immediate"]:9: in function 'test'
        [string "Immediate"]:13: in main chunk


However a slight modification seemed to work:


db=sqlite3.open(GetInfo (82))  -- open MUSHclient prefs file

mt = getmetatable (db)

mt.__index.test = function (self, arg)
  print "in test"
  return self:nrows (arg)
end -- function

require "tprint"

for row in db:test("SELECT * FROM sqlite_master") do
  tprint (row)
end

db:close()  -- close

Amended on Sun 14 Jun 2009 11:40 PM by Nick Gammon
Australia Forum Administrator #4
Quote:

assert (package.loadlib("sqlite3.dll","luaopen_luasql_sqlite3")) ()


SQLite is built into MUSHclient these days, you don't need this line.