Lua double results showing - lua

So my lua script is showing double results:
It should only show one of each type of fluid.
This is the part of the script :
function firstToUpper(str)
return (str:gsub("^%l", string.upper))
end
function dispTanks()
mon.setCursorPos(offsetPos, 1)
mon2.setCursorPos(offsetPos,1)
for i=1, #machines do
-- RC Tanks --------------------------------------------
if string.find(machines[i], "rcirontankvalvetile")
or string.find(machines[i], "rcsteeltankvalvetile") then
if peripheral.isPresent(machines[i]) then
periph = peripheral.wrap(machines[i])
fluidRaw, fluidName, fluidAmount, fluidCapacity, fluidID = marik.getTank(periph)
if fluidName == nil then
-- does not display empty tanks
elseif fluidName ~= nil then
mon2.setTextColor(tc)
x,y = mon2.getCursorPos()
mon2.setCursorPos(offsetPos, (y+1))
mon2.clearLine()
-- marik.cString(offsetPos,(y+1), tc, right, ",")
nameFL = firstToUpper(marik.comma(fluidName):match("[^.]*"))
mon2.write("Tank (" .. nameFL .. ") : " .. marik.getBuckets(fluidAmount) .. " buckets")
end
end
end
end
end
I though it was not ending the showing with a "," "." or a ")" but that doesn't seem to be the case. How can i fix this?
Pastebin edit
This are the 2 complete codes:
The main program : http://pastebin.com/ejVPwW4Q
The api : http://pastebin.com/uycrzMTy

After taking a look at this i would suggest taking a look into what your table looks like because the code posted above does not seem to have anything wrong with it, BUT if your table some how duplicated the machines then it would certainly print it out twice, that's where i would start to look.
Edit - and by table i mean the "array" machines
Code to debug the table "array" put this before the section of code you placed on your question..
for k, v in pairs(machines) do
print(tostring(k)..": "..tostring(v))
end

Related

Cycling through different file location options

I'm essentially trying to create a function which tests the first location I give, in the form:
myComputer.referenceLookup("/address/x/text")
and return the string in that location if it is not NULL or "None" or "" (empty).
If not, I want it to test the next possible location:
myComputer.referenceLookup("/address/1/x/text")
Otherwise, I would like it to return an empty string ("").
I've tried looking in the Lua Manual to no avail as well as testing different forms in repl.it, but unfortunately, I can't replicate a similar example as I usually do when testing.
function firstLine(x)
if myComputer.referenceLookup("/Address/ .. (x) .. /text") != NULL or "None" or "" then
return myComputer.referenceLookup("/Address/ .. (x) .. /text")
elseif myComputer.referenceLookup("/Address/1/ .. (x) .. /text") != NULL or "None" or "" then
return myComputer.referenceLookup("/Address/1/ .. (x) .. /text")
else
return ""
end
end
myComputer.out.firstHouseNumber = firstLine(housenumber)
It's worth noting that the usual way I would reference the fact is as follows:
myComputer.out.firstHouseNumber= myComputer.referenceLookup("/Address/housenumber/text")
or
myComputer.out.firstHouseNumber= myComputer.referenceLookup("/Address/1/housenumber/text")
The platform I'm using doesn't throw errors, it just will return blank instead of running the lua script so I am unable to debug (hence usually using repl.it).
I know this makes it a bit of an abstract question, but if anyone knows how I can do what I am describing, it would be very much appreciated.
Assumptions
Looking at your answer, I will assume that
myComputer.referenceLookup is defined somewhere else and works as intended (and not part of this question)
NULL is also defined somewhere else and represents some sort of nil-value
Answer
The line
if myComputer.referenceLookup("/Address/ .. (x) .. /text") != NULL or "None" or "" then
doesn't work, because the or operator doesn't work that way.
How Lua interprets it is
if (myComputer.referenceLookup("/Address/ .. (x) .. /text") != NULL) or "None" or ""
and since "None" is a String value and thus considered truthy, the if condition will always evaluate to true, so it will always return the first location. Also, there is no != operator in Lua; it's ~= instead.
As for a solution, you essentially need three comparisons like this:
if myComputer.referenceLookup("/Address/" .. x .. "/text") ~= NULL
and myComputer.referenceLookup("/Address/" .. x .. "/text") ~= "None"
and myComputer.referenceLookup("/Address/" .. x .. "/text") ~= "" then
Obviously calling the function three times is a bad idea, both because of performance and because it may have side effects, so it's better to save it into a variable first like so:
local result = myComputer.referenceLookup("/Address/" .. (x) .. "/text")
if result ~= NULL and result ~= "None" and result ~= "" then
return result
end
Extra
If you want to make your program easier to extend, you can also use string.format to build the locations from templates. Say you have a table containing all your locations like this:
local locations = {
"/Address/%s/text";
"/Address/1/%s/text";
}
Then you can iterate through the entries using ipairs and build each location using string.format:
for index, template in ipairs(locations) do
local result = myComputer.referenceLookup(template:format(x))
if result ~= NULL and result ~= "None" and result ~= "" then
return result
end
end
Note that you can write string.format(template, x) as template:format(x) as long as template is a string. (further reading)

Lua: gmatch multi line string?

I'm trying to make a function that searches through some code to find the line the search term is on, as well as the line's index. The code is a multi line string with new line characters. I was thinking of using gmatch to do this, but I have no clue how.
This is my code at the moment. It's awful, but I can't think of a way to make it any better:
local function search( code, term )
local matches = {}
local i = 0
for line in string.gmatch( code, "[^\r\n]+" ) do
i = i + 1
if string.find( line, term, 1, true ) then
table.insert( matches, { line = i, code = line } )
end
end
return matches
end
Any help would be appreciated!
Your solution seem fine to me. The problem with using a single gmactch loop is your requirement to report line numbers. The code below avoids this by embedding line numbers into the code. I've use # to mark line numbers. You can use any char that does not appear in the source code, even something like \0.
function search(code,term)
for a,b in code:gmatch("#(%d+):([^\n]-"..term.."[^\n]-)\n") do
print(a)
print(b)
end
end
local n=0
code="\n"..code
code=code:gsub("\n", function () n=n+1 return "\n#"..n..":" end)
search(code,"matc")

Why does my code throws a NON ZERO EXIT CODE runtime error while using Ruby language?

I am trying to solve a HackerEarth problem using Ruby
The problem is provided in the following link:
https://www.hackerearth.com/problem/algorithm/find-product/
My solution for the problem is here :
n = gets.chomp.to_i
a = Array.new
if n <= 1000
n.times do
a << gets.chomp.to_i
end
end
a.each { |m| print m.to_s + " " }
print "\n"
answer = 1
a.each do |m|
answer = ( answer * m ) % ( (10**9) + 7)
end
puts "#{answer}"
The code throws a Runtime Non zero exit code (NZEC).I am not able to understand the concept of NZEC and what particulary wrong I am doing in this code. Can someone pls help me to understand NZEC and find a work around for it.
The NZEC error appears because, you read the problem a bit quickly.
The first line must contain a single integer n, and the second line must contain each element separated by a space.
When I launch your script, it seems I need to press enter between each entry of the array. so when you test your code in hackerhearth I presume that execution failed because it receives no response after the second entry.
There is also a similar problem with your output, you print the full array before display the answer. The problem definition specifies you have to only display the answer.
One possible solution could be the following:
n = gets.chomp.to_i
a = gets.chomp.split.map(&:to_i)
answer = 1
a.each do |m|
answer = ( answer * m ) % ( (10**9) + 7)
end
puts "#{answer}"

Lua multiline comments past ]]'s

I'm trying to find out a way to use a multiline comment on a batch of code, but it keeps mistaking some syntax in it as a ]] and thinking I want it to end there, which I don't!
--[[
for k,v in pairs(t) do
local d = fullToShort[k]
local col = xColours[v[1]] -- It stops here!
cecho(string.format(("<%s>%s ", col, d))
end
--]]
I thought I read somewhere it was possible to do use a different sort of combination to avoid those errors, like --[=[ or whatnot... Could someone help?
As you can see in Strings tutorial there is a special [===[ syntax for nesting square braces. You can use it in block comments too. Just note, that number of = signs must be the same in open and close sequence.
For example 5 equals will work.
--[=====[
for k,v in pairs(t) do
local d = fullToShort[k]
local col = xColours[v[1]] -- It stops here!
cecho(string.format(("<%s>%s ", col, d))
end
--]=====]
You can use the following to create multiline comments past ]]'s:
--[[
codes
]]

Lua: If no value, then create value in table - What am I missing?

I have an issue that I've spent hours trying to figure out, but since Lua is still relatively new to me, I can't figure out why it's not working.
Here's what I'm trying to do. If I'm spiking an item for the first time, it won't show up in the spikeRates table, so I need to add it. If I've spiked the item before, but never with the item I'm spiking with, then I need to reflect that in the spikeRates[itemSpiked] table. The code I've written up is as follows, but fails to populate the table.
spikeRates={}
itemSpiked = "leather"
mySpike = "iron"
if not spikeRates[itemSpiked] then
spikeRates[itemSpiked]={}
spikeRates[itemSpiked][mySpike]={}
print("This is your first time spiking "..itemSpiked.."!")
elseif not spikeRates[itemSpiked][mySpike] then
spikeRates[itemSpiked][mySpike]={Failure=0,Success=0}
print("This is your first time spiking "..itemSpiked.." with "..mySpike.."!")
end
for i,v in pairs(spikeRates) do
print(i .. ": " .. v)
end
When that's run, I get an error of trying to concatenate a nil value (v) for the printing of the database. Everything looks correct, or so I thought. Am I missing something completely obvious? Thanks!
The if-else logic seems a bit confusing. Try separating it into two ifs, like so:
spikeRates={}
itemSpiked = "leather"
mySpike = "iron"
if not spikeRates[itemSpiked] then
spikeRates[itemSpiked]={}
print("This is your first time spiking "..itemSpiked.."!")
end
if not spikeRates[itemSpiked][mySpike] then
spikeRates[itemSpiked][mySpike]={Failure=0,Success=0}
print("This is your first time spiking "..itemSpiked.." with "..mySpike.."!")
end
for i,v in pairs(spikeRates) do
print(i .. ": " .. v)
end
If you don't need the debug prints, here's a simpler version with no ifs at all:
spikeRates={}
itemSpiked = "leather"
mySpike = "iron"
spikeRates[itemSpiked] = spikeRates[itemSpiked] or {}
spikeRates[itemSpiked][mySpike] = spikeRates[itemSpiked][mySpike] or {Failure=0,Success=0}
for i,v in pairs(spikeRates) do
print(i .. ": " .. v)
end
This variable = variable or defaultValue is a very common idiom in Lua, you will see it very often.

Resources