lua-users home
lua-l archive

Re: Style question for user-defined types in C

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


It was thus said that the Great Josh Haberman once stated:
> Suppose I have a user-defined type implemented in C.
> 
> x = mytype.new()
> 
> Suppose my type has both data members (ie. passive) and methods
> which actually perform an action. Is it preferred to use method
> calls for both?
> 
> x:do_something(5) -- Clearly should be a function.
> x:name() -- Called as a function, even though it's just data?
> x.name -- Returned as a string -- is this better?
 A project at work uses a custom read-only database file (could have
upwards of 100,000,000 small records; and they're pre-sorted as there's only
one key anyway). I wrapped Lua around this database file using the
following:
	x = cdb.open(filename)	-- opens database file, returns user data
	
 x itself has a metatable associated with it, and thus you can do:
	entry = x:find(key)	-- find the entry associated with key
	x:close()		-- close the file, free resources, etc.
	#x			-- number of entries in data file
	entry = x[23]		-- reference 23rd entry in data file
 What's returned from x:find() or x[index] is a Lua table that corresponds
to the particular entry (a string and a bunch of flags). Doing it this way
felt more natural than using a function to return an individual record. 
Looking back on this, I suppose I could have done:
	entry = x[key]
as well. Hmm ... I could add that ... 
 Anyway, I did provide methods for __tostring, __gc, __index, __newindex
(to remind the other programers we can't change the data) and __len. 
> Aesthetically the last one seems more pleasing, since it makes clear
> that it's just returning some data. But what do you all as Lua
> programmers expect? I guess one downside of the second is that
> it might suggest that you can set it also, which is not allowed
> for my type:
 In my case, it's what felt better for the project, seeing how I'm
embedding Lua in a larger application (a testing suite for the project). 
> I want to make whatever choices are most idiomatic, but if there
> are any noticeable efficiency differences that is a factor too.
 I just went with what looked good to me.
 -spc (We're mostly a C/C++ shop, so idiomatic Lua isn't our top priority 8-P

AltStyle によって変換されたページ (->オリジナル) /