I'm expecting 9, but getting nil. Not sure why.
> dfs = p.disk_items.inject { |acc, di| acc + 1 if di.type == "DiskFile" }
=> nil
The same problem:
> dfs = p.disk_items.inject(0) { |acc, di| if di.type == "DiskFile" then acc + 1 end }
=> nil
Clearly there are nine occurrences where di.type == "DiskFile" is true:
> dfs = p.disk_items.inject(0) { |acc, di| puts di.type == "DiskFile" }
true
true
true
true
true
true
true
true
true
false
=> nil
What am I screwing up? If I can't use conditionals, then maybe there's a better way to count all the ActiveRecord objects in an array that satisfies a condition on an attribute.
Edit: FWIW:
> p.disk_items.class
=> ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_DiskItem
looks like this implementation in Rails source of count may not accept blocks? Though I may be reading this wrong or looking in the wrong place...
user2246674 is correct, the if statement is returning nil, but inject should always return acc You can use a turnery operator to make this easy
dfs = p.disk_items.inject(0) { |acc, di| di.type == "DiskFile" ? acc + 1 : acc }
When the if "doesn't run" the block evalutates to nil. This happens on the last case and the result (nil) is returned.
Consider (the long-hand):
if di.type == "DiskFile" then
acc + 1
else
acc # so we never return nil
end
While there are various short-hands (i.e. ?:), I would use a count {block}. If needing to do something else with the values (perhaps still using in an inject "sometimes"), select might also be useful.
p.disk_items.count {|di| di.type == "DiskFile"}
Related
So I am working on a project and I need to split a string that would look something like this:
if (x == 2){ output("Hello") }
This is my code:
local function splitIfStatement(str)
local t = {}
t[1] = ""
t[2] = ""
t[3] = ""
local firstSplit = false
local secondSplit = false
local thirdSplit = false
str:gsub(".", function(c)
if c == "(" then
firstSplit = true
end
if firstSplit == true then
if c == "=" then
firstSplit = false
secondSplit = true
else
if c == "(" then
else
t[1] = t[1] .. c
end
end
end
if secondSplit == true then
if c == ")" then
secondSplit = false
thirdSplit = true
else
if c == "=" then
else
t[2] = t[2] .. c
end
end
end
end)
return t
end
I need to split the string at "(" so t[1] is only equal to "x" and t[2] is equal to 2 and then t[3] is equal to the "output()"
But when I run my code(note I haven't added the t[3]) t[1] returns: "x "Hello") }" and t[2] returns 2 like it should.
Anyways why isn't the split function working on the first split but it works on the second.
Thanks!
In your loop you set firstSplit true if it hits a ( this happens in 2 places in your example, before x and right before "Hello"
you can fix this by setting firstSplit true and ignore the leading if ( before you beginning the loop. Then you allow the logic you have to handle the rest.
I also notice you dont have any logic that references t[3] right now.
That all said you really should use a pattern to parse something like this.
local function splitIfStatement(str)
t = {str:match("if%s*%((%w+)%s*[=<>]+%s*(%d+)%)%s*{(.+)}")}
return t
end
this pattern is very narrow and expects a specific type of if statement, you can learn more about lua patterns here: Understanding Lua Patterns
If the input is of the form
if (AAA == BBB){ CCC("Hello") }
with possible whitespace around the fields in question, then this code works:
S=[[if (x == 2){ output("Hello") } ]]
a,b,c = S:match('%(%s*(.-)%s.-%s+(.-)%)%s*{%s*(.-)%(')
print(a,b,c)
Hi I am a user on Roblox and I am trying to script a light switch that turns off 4 lights and I am having a error (it's in the title)
There are 2 blocks being used, the Off4 and On4 switch.
My code is
function OnClicked()
if (workspace.LivingRoomLight.SpotLight.Enabled == true) and (workspace.LivingRoomLight2.SpotLight.Enabled == true) and (workspace.LivingRoomLight3.SpotLight.Enabled == true) and (workspace.LivingRoomLight4.SpotLight.Enabled == true) then
(workspace.LivingRoomLight.SpotLight.Enabled = false) and (workspace.LivingRoomLight2.SpotLight.Enabled == false) and (workspace.LivingRoomLight3.SpotLight.Enabled == false) and (workspace.LivingRoomLight3.SpotLight.Enabled == false)
script.Parent.Transparency = 1
workspace.Off4.Transparency = 0
end
end
script.Parent.ClickDetector.MouseClick:connect(OnClicked)
The other scripts (that work) I use in the ones that use only one light is
function OnClicked()
if (workspace.Hallwaylight.SpotLight.Enabled == true) then
workspace.Hallwaylight.SpotLight.Enabled = false
script.Parent.Transparency = 1
workspace.Off.Transparency = 0
end
end
script.Parent.ClickDetector.MouseClick:connect(OnClicked)
Note: I am only using the on scripts because that's the only one I edited for the one with the error. The error in the on script is the first = at column 3 and when I use '==' instead of '=' then the whole line becomes a error
Try this:
if (workspace.LivingRoomLight.SpotLight.Enabled == true) and (workspace.LivingRoomLight2.SpotLight.Enabled == true) and (workspace.LivingRoomLight3.SpotLight.Enabled == true) and (workspace.LivingRoomLight4.SpotLight.Enabled == true) then
workspace.LivingRoomLight.SpotLight.Enabled = false
workspace.LivingRoomLight2.SpotLight.Enabled = false
workspace.LivingRoomLight3.SpotLight.Enabled = false
workspace.LivingRoomLight4.SpotLight.Enabled = false
...
Some pointers:
x == y means “does x equal y?”. It’s a condition (either true or false).
x = y means “set x to y”. It’s a statement (a command to your program to modify the value of x).
and is an operator that expects conditions to its left and right.
Your program is of the form
if (these four values are true) then
set each of them to false
end
so you need and and == on the first line, but they don’t make sense inside the if — you need four simple statements using =, there.
You don’t really need == though. Comparing boolean values (like workspace.LivingRoomLight.SpotLight.Enabled, which are already true or false) to true is a bit silly: instead of if x == true then ... end it’s nicer to just write if x then ... end.
I need to check if a member exists in a table that isn't at the next level, but along a path of members.
foo = {}
if foo.bar.joe then
print(foo.bar.joe)
end
this will cast an attempt to index field 'bar' (a nil value) because bar isn't defined.
My usual solution is to test the chain, piece-by-piece.
foo = {}
if foo.bar and foo.bar.joe then
print(foo.bar.joe)
end
but this can be very tedious when there are many nested tables. Are there a better way to do this test than piece-by-piece?
I don't understand what you try to mean by "along a path of members". From the example, I assume you are trying to find a value in a "subtable"?
local function search(master, target) --target is a string
for k,v in next, master do
if type(v)=="table" and v[target] then return true end
end
end
A simple example. If you use such a function, you can pass the foo table and the joe string to see if foo.*.joe exists. Hope this helps.
debug.setmetatable(nil, {__index = {}})
foo = {}
print(foo.bar.baz.quux)
print(({}).prd.krt.skrz.drn.zprv.zhlt.hrst.zrn) -- sorry ))
To search for an element that is at any level of a table, I would use a method such as this one:
function exists(tab, element)
local v
for _, v in pairs(tab) do
if v == element then
return true
elseif type(v) == "table" then
return exists(v, element)
end
end
return false
end
testTable = {{"Carrot", {"Mushroom", "Lettuce"}, "Mayonnaise"}, "Cinnamon"}
print(exists(testTable, "Mushroom")) -- true
print(exists(testTable, "Apple")) -- false
print(exists(testTable, "Cinnamon")) -- true
I think you're looking for something along these lines:
local function get(Obj, Field, ...)
if Obj == nil or Field == nil then
return Obj
else
return get(Obj[Field], ...)
end
end
local foo = {x = {y = 7}}
assert(get() == nil)
assert(get(foo) == foo)
assert(get(foo, "x") == foo.x)
assert(get(foo, "x", "y") == 7)
assert(get(foo, "x", "z") == nil)
assert(get(foo, "bar", "joe") == nil)
assert(get(foo, "x", "y") or 41 == 7)
assert(get(foo, "bar", "joe") or 41 == 41)
local Path = {foo, "x", "y"}
assert(get(table.unpack(Path)) == 7)
get simply traverses the given path until a nil is encountered. Seems to do the job. Feel free to think up a better name than "get" though.
As usual, exercise care when combining with or.
I'm impressed by Egor's clever answer, but in general I think we ought to not rely on such hacks.
See also
The 'Safe Table Navigation' patch for Lua 5.2 : http://lua-users.org/wiki/LuaPowerPatches
Lengthy discussion on this matter : http://lua-users.org/lists/lua-l/2010-08/threads.html#00519
Related technique : http://lua-users.org/wiki/AutomagicTables
I suspect something relevant has been implemented in MetaLua, but I can't find at the moment.
If I understood your problem correctly, here's one possibility:
function isField(s)
local t
for key in s:gmatch('[^.]+') do
if t == nil then
if _ENV[ key ] == nil then return false end
t = _ENV[ key ]
else
if t[ key ] == nil then return false end
t = t[ key ]
end
--print(key) --for DEBUGGING
end
return true
end
-- To test
t = {}
t.a = {}
t.a.b = {}
t.a.b.c = 'Found me'
if isField('t.a.b.c') then print(t.a.b.c) else print 'NOT FOUND' end
if isField('t.a.b.c.d') then print(t.a.b.c.d) else print 'NOT FOUND' end
UPDATE: As per cauterite's suggestion, here's a version that also works with locals but has to take two arguments :(
function isField(t,s)
if t == nil then return false end
local t = t
for key in s:gmatch('[^.]+') do
if t[ key ] == nil then return false end
t = t[ key ]
end
return true
end
-- To test
local
t = {}
t.a = {}
t.a.b = {}
t.a.b.c = 'Found me'
if isField(t,'a.b.c') then print(t.a.b.c) else print 'NOT FOUND' end
if isField(t,'a.b.c.d') then print(t.a.b.c.d) else print 'NOT FOUND' end
foo = {}
foo.boo = {}
foo.boo.jeo = {}
foo.boo.joe is foo['boo']['joe'] and so
i make next function
function exist(t)
local words = {}
local command
for i,v in string.gmatch(t, '%w+') do words[#words+1] = i end
command = string.format('a = %s', words[1])
loadstring(command)()
if a == nil then return false end
for count=2, #words do
a = a[words[count]]
if a == nil then return false end
end
a = nil
return true
end
foo = {}
foo.boo = {}
foo.boo.joe = {}
print(exist('foo.boo.joe.b.a'))
using loadstring to make temp variable. my lua ver is 5.1
remove loadstring at 5.2 5.3, instead using load
I'm attempting to compare two tables of equal length with a function, since I don't know of any other way to do so. However, with the following function, it fails to register, and I've no clue why. I'm hoping someone can provide insight to this problem or has a better way of comparing the two tables.
The tables are being populated with the following code:
str = "parameters determined by program (all digits)"
tableone = {}
for word in str:gmatch("%d") do table.insert(tableone,word) end
It's identical for both tables, except, of course, the individual table names. The tables are being populated properly, and display properly when I print them. Here are two tables for the sake of this question:
tableone = {}
tabletwo = {}
for i=1,4 do table.insert(tableone, i) end
for i=1,4 do table.insert(tabletwo, i) end
Obviously, these two tables are going to be equal to each other. The function I wrote to compare the index tables is as follows:
function comparetables(t1, t2)
matchct = 0
for i=1,#t1 do
if t1[i] == t2[i] then
matchct = matchct + 1
end
if matchct == #t1 then
return true
end
end
I tried doing
print(comparetables(tableone,tabletwo))
to see if it'll print "true" but no luck. To me, it seems like it should work without a problem. Yet it doesn't. What am I missing? I've tried searching for something like a table.compare function that someone may have already written, but no such luck in finding one. Thanks for any suggestions!
Additional information:
The reason I'm comparing tables is for a mastermaind-type game. That means the following three rules must apply when comparing tables. The function I created was to just get me started, thinking I could work from there.
When comparing the tables, if the numbers match, Ccount increases by 1.
When comparing tables, if the value exists in a different index position, increment Pcount by 1
For example, with a table of values {1, 3, 3, 4} and a guess of {4, 4, 3, 1}, it would return Pcount of 2 (the one 4 and the 1) and a Ccount of 1 (the three in the third position). I think one of the hardest parts is going to be getting the comparison to recognize that the second 4 in the guess should not increment the Pcount at all.
A slight variant on your code that should work is:
function comparetables(t1, t2)
if #t1 ~= #t2 then return false end
for i=1,#t1 do
if t1[i] ~= t2[i] then return false end
end
return true
end
However I use something more like this: It checks the types of the arguments, their metatables, and a few other cases.
-- This is not clever enough to find matching table keys
-- i.e. this will return false
-- recursive_compare( { [{}]:1 }, { [{}]:1 } )
-- but this is unusual enough for me not to care ;)
-- It can also get stuck in infinite loops if you use it on
-- an evil table like this:
-- t = {}
-- t[1] = t
function recursive_compare(t1,t2)
-- Use usual comparison first.
if t1==t2 then return true end
-- We only support non-default behavior for tables
if (type(t1)~="table") then return false end
-- They better have the same metatables
local mt1 = getmetatable(t1)
local mt2 = getmetatable(t2)
if( not recursive_compare(mt1,mt2) ) then return false end
-- Check each key-value pair
-- We have to do this both ways in case we miss some.
-- TODO: Could probably be smarter and not check those we've
-- already checked though!
for k1,v1 in pairs(t1) do
local v2 = t2[k1]
if( not recursive_compare(v1,v2) ) then return false end
end
for k2,v2 in pairs(t2) do
local v1 = t1[k2]
if( not recursive_compare(v1,v2) ) then return false end
end
return true
end
Here's an example of it in use:
print( recursive_compare( {1,2,3,{1,2,1}}, {1,2,3,{1,2,1}} ) ) -- prints true
print( recursive_compare( {1,2,3,{1,2,1}}, {2,2,3,{1,2,3}} ) ) -- prints false
If you're comparing objects that are more objecty than tabley in an Object oriented sense, then I'd look at implementing the functions in the lua OO way.
Something like this should do the trick:
GameState = {}
GameState.mt = {}
GameState.mt.fns = {}
GameState.mt.__index = GameState.mt.fns
function GameState.new(a,b,c,d)
-- TODO: put argument checks here...
local retval = {}
retval[1] = a
retval[2] = b
retval[3] = c
retval[4] = d
setmetatable(retval, GameState.mt)
return retval
end
function GameState.mt.fns.print( self )
print(" GameState: ", self[1], self[2], self[3], self[4] )
end
function GameState.mt.__tostring( self )
return "GameState: "..self[1].." "..self[2].." "..self[3].." "..self[4]
end
function GameState.mt.__eq(self, other)
-- Check it's actually a GameState, and all its bits match
return getmetatable(other)==GameState.mt and
(self[1] == other[1]) and
(self[2] == other[2]) and
(self[3] == other[3]) and
(self[4] == other[4])
end
Then you'd use it like this:
state1 = GameState.new(1,2,3,4)
state2 = GameState.new(1,2,3,4)
print("State 1 is:")
state1:print()
print("State 2 is:")
print(state2)
print( "state1 == state2 : ", state1 == state2 )
print( "Changing state 2")
state2[1]=2
print( "state1 == state2 : ", state1 == state2 )
in ruby/rails3, I need to do some heavy text parsing to find a certain string. Right now I'm doing something like the following:
extract_type1 = body.scan(/(stuff)/m).size
extract_type2 = body.scan(/(stuff)/m).size
extract_type3 = body.scan(/(stuff)/m).size
extract_type4 = body.scan(/(stuff)/m).size
extract_type5 = body.scan(/(stuff)/m).size
if extract_type1 > 0
elsif extract_type2 > 0
elsif extract_type3 > 0
elsif extract_type4 > 0
elsif extract_type5 > 0
The problem here is that I keep needing to add extract types based on the app. And that results in a lot of processing when the case occurs that extract_type1 >0 and the rest aren't needed.
But at the same time, it's nice and clean to have the extract logic separated from the if block as that would be busy messy and hard to read.
Any thoughts on how to optimize this while not compromising readability?
Thanks
what about storing all your "keywords" you are searching for in an array and iterate over it like:
stuff = ["stuff1", "stuff2"]
stuff.each do |c_stuff|
if body.scan(/(#{Regexp.escape(c_stuff)})/m).size > 0
# do something
# break the loop
break
end
end
Edit: If you need the index of the element, you can use each_with_index do |c_stuff, c_index|
Lazy evaluation might work for you; just convert your extract_X variables to lambdas so that the values are computed on use:
extract_type1 = lambda { body.scan(/(stuff)/m).size }
extract_type2 = lambda { body.scan(/(stuff)/m).size }
extract_type3 = lambda { body.scan(/(stuff)/m).size }
extract_type4 = lambda { body.scan(/(stuff)/m).size }
extract_type5 = lambda { body.scan(/(stuff)/m).size }
if extract_type1.call > 0
elsif extract_type2.call > 0
elsif extract_type3.call > 0
elsif extract_type4.call > 0
elsif extract_type5.call > 0
If you're using the extract_X values more than once then you can add memoization to the lambdas so that the values are computed on first access and then cached so that subsequent accesses would just use the value that was already computed.