How to create a textview in Lua that keeps updating automatically i.e. different results can be displayed in the same textview.

57 views
Skip to first unread message

Rana Ayaz

unread,
Mar 6, 2024, 11:02:20 PM3/6/24
to lu...@googlegroups.com
I want to create a textview in Lua language that updates automatically.
I want to create a text view to display the digital time on the screen with the time updating continuously and viewable in a single text view..
Or create a text view for a news in which every new update is displayed in the same text view.
We can also set it for cricket score updates i.e. cricket score updates in a single text view.
I am posting a code below which displays the time on the screen but I don't know how to make the time update automatically in the same textview so that the time is updated and displayed..
I am currently using lua version 5.3 in my android mobile and this code is made by me for android only..
Please correct the below code and explain me how to create such a textview with time update..

require "import"
import "android.widget.*"
import "android.view.*"
import "android.graphics.*"
import "android.content.pm.ActivityInfo"

activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)

layout = LinearLayout(activity)
layout.setBackgroundColor(Color.BLACK)
layout.setGravity(Gravity.CENTER)
layout.setOrientation(1)

time = os.date("%I : %M %S")
text = TextView(activity)
text.setText(time)
text.setTextSize(150)
text.setGravity(Gravity.CENTER)
text.setTextColor(Color.WHITE)
layout.addView(text)

activity.setContentView(layout)

Paul Merrell

unread,
Mar 7, 2024, 2:27:16 AM3/7/24
to lu...@googlegroups.com

You may find these excerpts helpful from the NoteCase Pro Help file: 

This branch includes resources for scripts that handle dates and times.

See also in the Help file scriptable program commands that can also handle dates and times under the Date Property Commands and Custom Property Commands topics.


Table of contents


Calculating Day of Week

--[[

NoteCase Pro script

   See http://www.notecasepro.com/


SCRIPT NAME: Insert Event Date Property

   v. 1.0.0


PURPOSE: Script pops up a text entry dialog for entry of a date in YYYY-MM-DD format. When the dialog's OK button is pushed, an event date custom property is created with the entered date as its value.

This is a script for use in creating a timeline in the List Pane. With the Event Date custom property active in the List Pane Columns Bar, clicking on that column's header will sort the listed notes in event date order, producing the timeline.

Use in conjunction with the "Remove Notes from List with No Event Date" script to remove notes from the list that have no Event Date custom property. Located in the Cornucopia Scripts menu under Lists & NoteGroups Menu > Process Listed Notes Menu > Remove Notes from List.


RIGHTS: This script's author, Paul E. Merrell, hereby waives all copyright and related or neighboring rights to this script, pursuant to the Creative Commons CC0 Universal relinquishment of rights found at http://creativecommons.org/publicdomain/zero/1.0/


CHANGE LOG:


TODO:

--]]

-- gets this script's document ID
nScriptDocID =   Nc_Script_DocID_Get()

-- gets IDs for current document
nDocID = Nc_Doc_ID_GetCur()

-- sets dimensions for InfoBoxes
local nDisplayWidth, nDisplayHeight = Nc_Env_DisplaySize_Get(0)
local nDlgWidth = .25 * nDisplayWidth
local nDlgHeight = .20 * nDisplayHeight

-- gets current Note ID
local strNoteID = Nc_Note_ID_GetCur(nDocID)
if strNoteID == "" then
  Nc_GUI_InfoBox("ERROR: A note must be selected before executing this action. The action will terminate without making any changes.", 1, "ERROR", nDlgWidth, nDlgHeight)
  return
end

-- aborts if note or document is read-only
-- loads and executes Test_Read_Only_Properties Function
Nc_Script_Execute(nScriptDocID, "M5DSbhiT6x6kzVBbr6eaOw")
local strErrMessage, bTerminate = Test_Read_Only_Properties(nDocID, strNoteID)

-- if either doc or note are read-only
if bTerminate == true then

  --     throws appropriate error message and terminates script
  local nDisplayWidth, nDisplayHeight = Nc_Env_DisplaySize_Get(0)
    local nDlgWidth = .35 * nDisplayWidth
    local nDlgHeight = .30 * nDisplayHeight
    Nc_GUI_InfoBox(strErrMessage, 1, "ERROR", nDlgWidth, nDlgHeight)

  return

end --if bTerminate == true

-- gets current date for use as suggested event date
local strTodayDate = os.date("%G:%m%e")

Nc_GUI_InfoBox(strTodayDate, 1, "Debug")

 
--[[
-- sets input dialog's dimensions
local nDisplayWidth, nDisplayHeight = Nc_Env_DisplaySize_Get(0)
local nDlgWidth = .25 * nDisplayWidth
local nDlgHeight = .15 * nDisplayHeight

-- gets user's input date
local strDate = Nc_GUI_InputDlg("Input Event Date", [string strSuggestedValue, string strCancelReturnValue, int bHideCharacters, int bSingleLine, string strDescription, int bEnableRawHtmlPaste, int nDlgWidth, int nDlgHeight, int bWrapText])

--]]

Date and Time Lua Library

Date and Time library for Lua 5.x, public domain, http://luaforge.net/projects/date/ (Another page says about this library: "Pure Lua Date & Time module for Lua 5.x featuring date and Time string parsing, time addition & subtraction, time span calculation, support for ISO 8601 Dates, local time support, strftime-like formatting.")

Site says it's for use in a console. But platform agnostic.



Day Of Week And Days In Month Example

"The following code provides date functions that include calculating the number of days in a given month and the day of week for a given calendar day."

http://lua-users.org/wiki/DayOfWeekAndDaysInMonthExample

Display Calendar In Html

Displays a Calendar in HTML

http://lua-users.org/wiki/DisplayCalendarInHtml.

LuaDate2

LuaDate v2

Lua Date and Time module for Lua 5.x.

Features:
  * Date and Time string parsing.
  * Time addition and subtraction.
  * Time span calculation.
  * Support ISO 8601 Dates.
  * Local time support.
  * Lua module (not binary).
  * Formats Date and Time like strftime.

Pasted from: http://math2.org/luasearch-2/luadist-extract/luadate-2.dist/luadate-2.src/README

Lua-Time

Lua-Time library, https://github.com/leite/lua-time. Basic date/time functions for Lua, with millisecond precision.

Luatz

A lua library for time and date manipulation.

Features include:
  - Normalisation of broken down date objects
      - allows for complex time/date manipulation logic e.g. "What day
is it in 2 days, 5 hours from now?"
  - Conversion between locations (time zones) using your local
zoneinfo database.
  - stftime style formatting

Currently hosted on github (along with documentation and examples):
https://github.com/daurnimator/luatz
Available via MoonRocks:
https://rocks.moonscript.org/modules/daurnimator/luatz/0.3-1
Source download: https://github.com/daurnimator/luatz/releases/tag/v0.3

Measuring Execution Time

With Lua, you can measure the execution time for a script or a script chunk by using the Lua os.clock function. That function returns an approximation of the operating system's current time in seconds (including decimal fractions of a second.)

The trick is to get the time at the beginning of the chunk or script, getting it again at the end of the chunk pr script, then subtracting to get the elapsed time.

Note that you can identify a portion of your code that is slowing things down by repeating such lines before and after different portions of your code.

Example Code:

    nClock = os.clock()

    -- do some scripted action here

    Nc_GUI_InfoBox("Elapsed time is: " .. os.clock()-nClock)


You can also repeat actions to accumulate enough results to exaggerate differences so you can tell which of multiple methods are the fastest where the differences are too tiny to be discerned by a single execution of each method.

For example, the following two scripts inform us that a particular unanchored pattern with capture search of a string 999,999 times is about 22 times slower than the same search and capture if the pattern is anchored to the beginning of the searched string.

    s = "the quick brown fox jumps over the lazy dog"
    w = "foo"

    strPat = ".*()" .. w
    nClock = os.clock()
    for i=1,999999 do s:find(strPat) end
    Nc_GUI_InfoBox(
("Elapsed time: " .. os.clock()-nClock)

    strPat = "^.*()" .. w
    nClock = os.clock()
    for i = 1,999999 do s:find(strPat) end
    Nc_GUI_InfoBox("Elapsed time: " .. os.clock()-nClock)

   

Rosetta Code Lua Snippets

Category: Lua, at RosettaCode.org. Includes links to snippets for date handling:

  Date format
  Date manipulation
  Day of the week
  Leap year


http://rosettacode.org/wiki/Category:Lua

There may be others on that site that weren't categorized properly.

Seconds Delay

--- Delay for a number of seconds.
-- @param delay Number of seconds
function delay_s(delay)
    delay = delay or 1
    local time_to = os.time() + delay
    while os.time() < time_to do end
end

Sleeping Scripts

Clean sleep method using a repeat … until loop, by Peter Odding, http://lua-users.org/lists/lua-l/2008-03/msg00213.html:

function wait(seconds)
  local start = os.time()
  repeat until os.time() > start + seconds
end

for i=1,10 do
  print(i)
  wait(7)
end

See also large page of methods at http://lua-users.org/wiki/SleepFunction.

Daniel Hertrich's method:

I implemented a relatively simple way to wait for the reply, using a
custom timeout (set to 5 seconds here):


-- send HTTP request
strQuery =  "GET " .. strVersionUrlUri .. " HTTP/1.1\r\nHost: " ..
strVersionUrlHost .. "\r\n\r\n"
   net.write(nSocket, strQuery)
     t1 = os.time()
        -- read HTTP response
        strReply = ""
        bFirstRead = true
        nTimeoutSec = 5

        repeat
          if bFirstRead == true then
            repeat nSize, strChunk = net.read(nSocket)
              until strChunk ~= "" or os.difftime(os.time(), t1) > nTimeoutSec
          else
           nSize, strChunk = net.read(nSocket)
          end
          strReply = strReply .. strChunk
         bFirstRead = false
       until nSize <= 0

 * posix.unistd.sleep [1]
 * posix.time.nanosleep [2]
 * posix.curses.napms [3]
 * ngx.sleep [4]

[1] https://luaposix.github.io/luaposix/modules/posix.unistd.html#sleep
[2] https://luaposix.github.io/luaposix/modules/posix.time.html#nanosleep
[3] https://luaposix.github.io/luaposix/modules/posix.curses.html#napms
[4] http://wiki.nginx.org/HttpLuaModule#ngx.sleep

Suspending/Resuming a Script

Suspend/resume a Lua script using coroutines: http://stackoverflow.com/questions/6145059/how-to-suspend-resume-processing-of-a-lua-command.

Time Zone Manipulation

Time Zone, Lua function that portably returns a timezone string in the form +hhmm or -hhmm, http://lua-users.org/wiki/TimeZone.

luatz, a lua library for time and date manipulation, allowing conversion of time between time zones. https://github.com/daurnimator/luatz.

Unit Conversion Function

"This code provides a convert_to function that converts between any two units on a scale defined in a table in pairs of {name, equivalent number of previous unit}. The example given is time, but it can be adapted for Imperial units, military divisions, pre-decimalisation British pounds, or any other incremental system of measurement."

http://lua-users.org/wiki/UnitConversion

Tested with NoteCase Pro. Works well. -- PEM

--
[Notice not included in the above original message:  The U.S. National Security Agency neither confirms nor denies that it intercepted this message.]
                                                ¯\_(ツ)_/¯

Rana Ayaz

unread,
Mar 7, 2024, 12:15:03 PM3/7/24
to lu...@googlegroups.com
Thank you very much sir
You have answered in great detail.
And you have sent many links which can be very helpful for me to learn many new things..
There are many things in them which are completely new to me and with the help of these links I will be able to learn them as well.
Thank you very much for all of them.

--
You received this message because you are subscribed to the Google Groups "lua-l" group.
To unsubscribe from this group and stop receiving emails from it, send an email to lua-l+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/lua-l/CAJ1g4g8uL%3DhHjvVyuyAK_gdmGEZmVGyzQWj92-%3DpQqG4KE%3Dg0Q%40mail.gmail.com.
Reply all
Reply to author
Forward
0 new messages