What does a method look like in a lua table - methods

The title says most of it but in case it does not entirely make sense what i mean is that a piece of data in a table looks like this:
local myTable = {"banana","apple"}
-- or
local myTable = {["banana"] = 1,["apple"]=2,}
-- functions look like this:
local myTable = {
function banana(args) print(args) end,
-- or
apple = function(args) print(args) end
}
but im not sure what a method looks like... sure i can make them outside of the table but i would prefer it to be in the table... however when i looked the normal "dictionary/library" i did not really see anything that looked like what i needed

What you might mean by method in lua is a function in a table.
t={method=function(a) return a end}
You can call this function like this:
t.method(2)--returns 2
However if you call this function with a colon : it passes table t as first argument:
t:method()--returns 't'
t:method(2)--still returns 't'
In fact it is equivalent to call it like this:
t.method(t)--returns t
Also it is cutomary to name the first argument self if it is intended to use as a 'method'. So:
t={method=function(self, a) return a end}
t.method()--returns nil
t.method(1)--returns nil
t.method(1, 2)--returns 2
t:method()--returns nil
t:method(1)--returns 1
t:method(1, 2)--returns 1

Related

Better ternary condition

Method find_something may return nil. In the following code,
something = find_something(id) ? find_something(id) : create_something(foo)
find_something(id) is called twice. This is a smell that I want to avoid. Is there a way to avoid redundancy in this expression?
Anything like this?
something = find_something(id) || create_something(foo)
There's not quite enough detail given to say this with confidence, though it might be this is a case for find_or_create_by.
If this does suit, you would just do:
something = YourModel.find_or_create_by(id: id)
You can also provide a block to this, which is passed to the create method if no record is found. For example:
something = YourModel.find_or_create_by(id: id) do |instance|
# this block only gets executed on create
instance.some_new_attribute = 'goes here'
end
Hope that's useful - let me know if it suits your use case.

Database query using array in ruby

I'm trying to find all rows with value in array, This is my code
require 'sqlite3'
db = SQLite3::Database.new('test.sqlite')
res = db.query("SELECT w1.synsetid
FROM words w1
WHERE w1.wordid IN (?)", arr)
arr: array of strings
And I get this error
SQLite3::RangeException: bind or column index out of range
Any Help?
The second argument to query is meant to be an array of placeholder values:
- (Object) query(sql, bind_vars = [], *args)
This is a convenience method for creating a statement, binding
paramters to it, and calling execute:
The query method doesn't know that it should treat your arr array specially, it just sees one placeholder and multiple values.
I think you have to do this this hard way: build the appropriate number of placeholders and paste them into the SQL. Something like this:
placeholders = (['?'] * arr.length).join(',')
res = db.query("select ... where w1.wordid in (#{placeholders})", arr)
You know exactly what is in placeholders so you don't have to worry about using string interpolation and injection issues when building your SQL like this.
If you're using Rails already then you could also wrap your SQLite tables with ActiveRecord and then use the usual ActiveRecord interface:
words = Word.where(:wordid => arr)

Tkinter Error when using Entry Delete Method

In my game, I have an __init__ function which creates a set of seven entry boxes, like so:
self.string1 = StringVal()
self.entry1 = Entry(frame, textvariable = self.string1).grid(row = 4, column = 1, sticky = W)
This is copied six more times. This works.
At the end of the game, though, I want to delete the Entry box's text, using this code I found several places online:
self.entry1.delete(0, END)
I also tried using something else I found:
if self.entry1.get():
self.entry1.delete(0, END)
These both say that self.entry1 is a NoneType object, and has no method .get() or .delete(). Just to try things out, I substituted self.entry1.get() and self.entry1.delete(0,END) with self.string1.get(), etc. I also tried substituting .delete(0, END) with .delete(0.0, END). Neither of these worked either. I do not understand what I am doing wrong.
Thanks for your help!
When you do something like this:
self.foo = Button(...).grid(...)
... Then what gets stored in self.foo is the result of the call to grid(). This will always be None. You need to separate your widget creation from the loyout in order to save a reference to the created widgets.

Single Ruby Value in One Line From a Collection

I have a collection of objects. There are 3 properties in each object
'id', 'name', 'is_primary'
The collection of objects will usually have anywhere from 1 to 5 objects.
What I want to do is check the collection to see if is_primary is true. If so output the name, or at least return it.
I want to do this in 1 line of code if possible. I am trying to slim up this one line for erb output in rails. Later in the page i'll output them all. I thought I had it, but if I return nil it adds extra space which shifts all the html oddly.
Thanks.
Hmm, this doesn't quite work if no element is_primary...I'm still thinking...
c.detect(&:is_primary).name
Ok, how about:
((a = c.detect(&:is_primary)) && a.name).to_s
As it happens, it is OK in an erb template for the <%= expression to return nil, that just results in an empty string, so for that case you can use:
(a = c.detect(&:is_primary)) && a.name
Update: Responding to the first comment, I do have a test case that I didn't post...
class A; attr_accessor :is_primary, :name, :id; end
t = [A.new, A.new, A.new, (a = A.new; a.name = 'xyz'; a.is_primary = true; a)]
puts (a = t.detect(&:is_primary)) && a.name
puts ((a = [].detect(&:is_primary)) && a.name).to_s
Complementing #DigitalRoss, you can also write:
collection.detect(&:is_primary).try(:name) || "default_if_no_element_or_name"
(well, to be honest I prefer Ick's maybe over Rails' try: c.detect(&:is_primary).maybe.name)
Side note: IMHO a flag that can only be active for a row it's not such a good idea. You may have inconsistent states with more than one being active and you'll have worry about it when updating (transactions, and so on). Try to store the PK reference somewhere else (a parent model? a state model?).
I want to do this in 1 line of code if possible. I am trying to slim up this one line for erb output in rails. Later in the page i'll output them all.
No need for one-liners (funny since I just wrote one): move the code to yous models or helpers as appropriate and keep your views pristine.

How do I evaluate non-SQL logic within a SQL call with ActiveRecord?

I'm new to Ruby and trying to make an ActiveRecord where call.
I also want to evaluate logic during the call, so that I get an object returned where the SQL query and my logic is true.
def new_target
#Need to make sure the array doesn't include the existing target
t = robot.where(
"name != :robot_name",
{:robot_name => self.name}
).first
I'd like to say something like !self.targets.include? (the returned robot).
So I'm searching for all robots that have a different name than the current one, but want to make sure I don't already have them within this robot's target array.
You code can be something like
t=robot.where(
"name!= :robot_name and name not in (:target_names) ",
{
:robot_name => self.name,
:target_names => self.targets.map{|robot| robot.name}
}
)

Resources