I'm unsure where to look as far as what I could use to capture a variable change in a program loaded within another program.
Here's my code, as messy as it is:
function launch()
shell.run("clear")
print("Preparing for first time run.")
sleep(1)
print("")
local program = netTest()
local file = loadstring(program)
file()
sleep(3)
shell.run("clear")
end
function netTest()
local output = http.get("http://pastebin.com/raw.php?i=hzZv3YH2")
if output then
local contents = output.readAll()
output.close()
return contents
else
print("Empty response")
return false
end
end
local program = netTest()
local file = loadstring(program)
launch()
Here's the code it's calling on:
function ping()
fails = 0
pingResult = 0
print("Testing Internet Connection.")
print("")
oldx, oldy = term.getCursorPos()
print("Connection Test 1")
http.request("http://www.google.com/")
if os.pullEvent() == "http_success" then
local oldx, oldy = term.getCursorPos()
term.setCursorPos(46,oldy-1)
io.write("Passed")
else
local oldx, oldy = term.getCursorPos()
term.setCursorPos(46,oldy-1)
io.write("Failed")
fails = fails+1
end
sleep(1)
print("Connection Test 2")
http.request("http://www.microsoft.com/")
if os.pullEvent() == "http_success" then
local oldx, oldy = term.getCursorPos()
term.setCursorPos(46,oldy-1)
io.write("Passed")
else
local oldx, oldy = term.getCursorPos()
term.setCursorPos(46,oldy-1)
io.write("Failed")
fails = fails+1
end
sleep(1)
print("Connection Test 3")
http.request("http://www.example-failure.com/")
if os.pullEvent() == "http_success" then
local oldx, oldy = term.getCursorPos()
term.setCursorPos(46,oldy-1)
io.write("Passed")
else
local oldx, oldy = term.getCursorPos()
term.setCursorPos(46,oldy-1)
io.write("Failed")
fails = fails+1
end
sleep(1)
if fails == 0 then
print("")
print("")
print("Test Complete, no failures detected.")
sleep(1.5)
elseif fails == 1 then
print("")
print("")
print("1 connection failures detected. A Website Host might be down however connectivity is still there.")
print("")
print("Test Complete.")
sleep(1.5)
elseif fails == 2 then
print("")
print("")
print("2 connection failures detected. Possible limited web connectivity.")
print("")
print("Test Complete.")
sleep(1.5)
elseif fails == 3 then
print("")
print("")
print("Catastrophic connection failure detected. A firewall or improper internet settings may be the problem.")
print("")
print("Test Complete.")
pingResult = __pingResult + 3
sleep(1.5)
end
end
ping()
What it's doing as you can see is running a program externally which will test the connection by making http requests to a couple pages to make sure there's connection to the internet. (I know, it's a bit lame, but I'm still learning).
Basically when and if the connection reads failure on all 3 stages, it'll make my pingResult variable = 3. What I'm wanting to do from the first program that called on my internet utility is record what that variable is set to. If it's set to 3 upon closing, to record that variable being set, and then for simplicity's sake, print that variable so I can see it's either 0 or 3. I'll be doing something with it later but you get the gist of it.
I've tried a couple other things but can't seem to figure out on how I go about doing this. Seeing as I'm still new I tried random stuff but none seemed to work, or I just did them wrong so I don't know what to do with it. Been trying at this one for a couple days to no success.
First of all, most of the code you posted is noise -- print statements, cursor manipulation, fetching Lua code from pastebin (?), all kinds of logic which has absolutely nothing to do with your question, including code which literally does nothing. That's why you haven't got a response yet.
See: How to Ask Questions the Smart Way: Volume is Not Precision.
If we strip all the extraneous stuff from your post, we're left with:
-- main.lua
local file = loadfile('nettest.lua')
file()
-- nettest.lua
pingResult = 123
Now to address your questions:
What it's doing as you can see is running a program externally:
It's not running anything externally. You've grabbed external code, but it's executed locally. Any changes that code makes to the global state is visible to you. In this case, main.lua has access to pingResult. For instance, you can write:
-- main.lua
local file = loadfile('nettest.lua')
file()
print(pingResult)
Of course, if you want a cleaner separation between your script and ping module, you should probably have that code return a value rather than write to a global:
-- main.lua
local file = loadfile('nettest.lua')
local pingResult = file()
print(pingResult)
-- nettest.lua
local pingResult
-- ... code the computes the result an stores it in pingResult ...
return pingResult
Related
I made this code thinking it would allow the player to jump Twice and the second Jump be the power of its leader stat but Instead it doesn't even allow the player to Jump a second time.
local UIS = game:GetService("UserInputService")
local player = game.Players.LocalPlayer
local character
local humanoid
local canDoubleJump = false
local hasDoubleJumped = false
local oldPower
local time_delay = 0.2
local jump_multiplier = player.leaderstats.JumpBoost.Value
function onJumpRequest()
if not character or not humanoid or not
character:IsDescendantOf(workspace) or humanoid:GetState() ==
Enum.HumanoidStateType.Dead then
return
end
if canDoubleJump and not hasDoubleJumped then
hasDoubleJumped = true
humanoid.JumpPower = oldPower * jump_multiplier
humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
end
local function characterAdded(new)
character = new
humanoid = new:WaitForChild("Humanoid")
hasDoubleJumped = false
canDoubleJump = false
oldPower = humanoid.JumpPower
humanoid.StateChanged:connect(function(old, new)
if new == Enum.HumanoidStateType.Landed then
canDoubleJump = false
hasDoubleJumped = false
humanoid.JumpPower = oldPower
elseif new == Enum.HumanoidStateType.Freefall then
wait(time_delay)
canDoubleJump = true
end
end)
end
if player.Character then
characterAdded(player.Character)
end
player.CharacterAdded:connect(characterAdded)
UIS.JumpRequest:connect(onJumpRequest)
I expected the player to Jump Twice with the second Jump having the power of the leader stat(I only put that and this because it says it wants more detail)
LocalScripts do not execute in game.Workspace: they only run on clients, hence the term 'local'; Scripts, on the other hand, are server-side.
You could use a Script to place your double-jump script--a LocalScript--into incoming players' character models.
-- Server-side Script
local players = game:GetService("Players")
local jumpScript = script:WaitForChild("JumpScript") -- Assume the double-jump script is a LocalScript called 'JumpScript'.
players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(char)
-- Check to make sure the character model does not already contain the double-jump script, just in case.
local clone = char:FindFirstChild("JumpScript")
if (not clone) then
clone = jumpScript:Clone()
clone.Parent = char
end
end)
end)
As a note, it is good practice to put server-side scripts like this into ServerScriptStorage instead of workspace or Lighting. (You can read about the safety of ServerScriptStoragehere.)
I have a part of a lua script here:
local cmp = require("component")
local r = cmp.br_reactor
local e = require("event")
local unicode = require ("unicode")
local exit = false
local buffersize = 10000000
local last_tick_percent = 1
print(type(last_tick_percent))
function stored_energy()
local rf_stored = r.getEnergyStored()
local rf_percent = (rf_stored/buffersize)*100
print(type(rf_precent))
print(type(last_tick_percent))
local delta_percent = rf_percent - last_tick_percent
last_tick_percent = re_percent
return rf_percent.."% ["..rf_stored.."] | "..unicode.char(916)..": "..delta_percent.."%"
end
The first print is not even executed for some reason. Inside the function, the first print returns Number while the second print returns nil.
Now I am getting the error attempt to perform arithmetic on upvalue "last_tick_percent" ( a nil value), obviously because last_tick_percent is nil which the print(type(..)) showed.
But i just assigned it literally 5 lines above.
So the questions are:
Why is last_tick_percent nil and how can i fix that?
why is the first print not executed?
you are assigning re_percent which is not declared in your script to last_tick_percent inside stored_energy. i am assuming you meant to assign rf_percent.
I am debugging an intermittent test failure. For this purposes I want to dump a lot of debug information if a test failed. Dumping debug stuff is quite slow process which produces a lot of data, so I do not want to do this for every test.
I am using pytest and yield autouse fixture should work great
#pytest.yield_fixture(scope="function", autouse=True)
def dump_on_failue(request):
prepare_debug_dump()
yield
if test_failed(request):
debug_dump()
The problem is that I can't figure out how do I detect whether test has failed or not. There was a questions already and even note on pytest website:
if request.node.rep_setup.failed:
print ("setting up a test failed!", request.node.nodeid)
elif request.node.rep_setup.passed:
if request.node.rep_call.failed:
print ("executing test failed", request.node.nodeid)
Unfortunately this code does not work anymore. There are no rep_setup and rep_calls symbols in node object. I tried to dig request and node object, but no luck.
Anybody knows how to detect whether test failed?
There are no rep_setup and rep_calls symbols in node object.
No.rep_setup and rep_calls symbols are still there.
Add this code into your root conftest.py. It will check pass/fail for every test function.
import pytest
#pytest.mark.tryfirst
def pytest_runtest_makereport(item, call, __multicall__):
rep = __multicall__.execute()
setattr(item, "rep_" + rep.when, rep)
return rep
#pytest.fixture(scope='function', autouse=True)
def test_debug_log(request):
def test_result():
if request.node.rep_setup.failed:
print ("setting up a test failed!", request.node.nodeid)
elif request.node.rep_setup.passed:
if request.node.rep_call.failed:
print ("executing test failed", request.node.nodeid)
request.addfinalizer(test_result)
I use something like this, maybe it can be useful in your case:
#pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item):
outcome = yield
rep = outcome.get_result()
if rep.failed:
if rep.when == "setup":
print("Setup failed!")
elif rep.when == "call":
print("Test method failed")
elif rep.passed and rep.when == "call":
print("Test {} passed.".format(item.name))
function saveScore()
local path = system.pathForFile("scoredata001.txt", system.DocumentsDirectory)
local file = io.open(path, "w")
if file then
local score=get_score() --The get_score() returns the value of current score which is saved in 'score'.
local newScore = compareScore()
local contents = tostring( newScore )
file:write( contents )
io.close( file )
return true
else
print("Error: could not write Score")
return false
end
end
function loadScore()
local path = system.pathForFile("scoredata001.txt", system.DocumentsDirectory)
local contents = ""
local file = io.open( path, "r" )
if file then
local contents = file:read( "*a" )
local score = tonumber(contents);
io.close( file )
return score
end
print("Could not read scores from scoredata.txt")
return nil
end
function return_highScore()
local highscore=loadScore()
if highscore==nil then
highscore=0
end
return highscore
end
function compareScore()
local highscore=return_highScore()
if highscore then
local currscore=get_score()
if highscore==0 then
return highscore
elseif currscore>highscore then
return currscore
end
end
return true
end
function disp_permScore()
local display_score=return_highScore()
text_display2= display.newText("GAME OVER!\n BEST: " ..display_score, 0, 0, "Helvetica", 80)
text_display2.x = centerX
text_display2.y = centerY
text_display2.alpha=1
function gameOver()
mainScreen()
saveScore()
disp_permScore()
end
(This is with refernce to previous question Permission issues in lua )
Basically I'm trying to build a game in lua (This is my first ever game)
But, I'm unable to save highscore to file. If it gets saved, then I'm unable to retrieve them. (In short, I always some or the other error/problem in executing the code.
Please have a look at the code above. I want to display both high score and current score. Current score is being displayed perfect. This is something I tried yesterday night. But now, the high score is not being saved in file. (i.e. the best always displays 0) Also, the cmd says "unable to read scores form scoredata.txt) I'm unable to find where I went wrong.
Please help with this?
Please tell where do I go wrong?
Also, if possible, provide (or edit) the correct code please?
There seems to be a problem on this line
if highscore==0
then
return highscore
Meaning you check if the highscore is 0 and if it is then you return it instead of the actual higher score.
Also, I don't know if your code was just pasting error, but without indenting your code it becomes really hard to read. Try and look again I indentet it and now the error becomes really easy to spot.
Situation :
There are two sensors and I want to save the data of values of each sensor in the certain file..But it's not working. I am working on linux system and the file is still empty.
What's wrong with my code? any suggestion please?
my code is:
--Header file
require("TIMER")
require("TIMESTAMP")
require("ANALOG_IN")
function OnExit()
print("Exit code...do something")
end
function main()
timer = "TIMER"
local analogsensor_1 = "AIR_1"
local analogsensor_2 = "AIR_2"
local timestr = os.data("%Y-%m-%d %H:%M:%S")
-- open the file for writing binary data
local filehandle = io.open("collection_of_data.txt", "a")
while true do
valueOfSensor_1 = ANALOG_IN.readAnalogIn(analogsensor_1);
valueOfSensor_2 = ANALOG_IN.readAnalogIn(analogsensor_2);
if (valueOfSensor_1 > 0 and valueOfSensor_2 > 0) then
-- save values of sensors
filehandle:write(timestr, " -The Value of the Sensors: ", tostring(valueOfSensor_1), tostring(valueOfSensor_2)"\n");
end
TIMER.sleep(timer,500)
end
-- close the file
filehandle:close()
end
print("start main")
main()
I do not know what this libs realy do.
But this code is incorrect;
1) you do not close while statement.
if in real code you close it before filehandle:close() then try call filehandle:flush()
2) you forgot comma:
filehandle:write(timestr, " -The Value of the Sensors: ", tostring(valueOfSensor_1), tostring(valueOfSensor_2)"\n")
(it should seay something like attemt call a number value).
3) try print out valueOfSensor_1 and valueOfSensor_2 values. May be there no data.
Beside the typos pointed out by #moteus, shouldn't this:
if (valueOfSensor_1 and valueOfSensor_2 > 0) then
be like this?
if (valueOfSensor_1 > 0 and valueOfSensor_2 > 0) then
Edit, in response to your comment to another answer:
still error..it says "attempt to call field 'data' (a nil value)
I can't be sure without the stack trace, but, most likely, something bad happens in the ANALOG_IN library code. You may not be using it properly.
try to turn this:
valueOfSensor_1 = ANALOG_IN.readAnalogIn(analogsensor_1);
valueOfSensor_2 = ANALOG_IN.readAnalogIn(analogsensor_2);
into this:
success, valueOfSensor_1 = pcall(ANALOG_IN.readAnalogIn, analogsensor_1);
if not success then
print("Warning: error reading the value of sensor 1:\n"..valueOfSensor_1)
valueOfSensor_1 = 0
end
success, valueOfSensor_2 = pcall(ANALOG_IN.readAnalogIn, analogsensor_2);
if not success then
print("Warning: error reading the value of sensor 2:\n"..valueOfSensor_2)
valueOfSensor_2 = 0
end
If the failure in ANALOG_IN is not systematic, it will work around it. If the call fails systematically, you'll get a huge warning log, and an empty collection_of_data.txt.
Please note that ANALOG_IN is not a standard Lua library. You should check its documentation , and pay attention to the details of its usage.