In Pascal, I have write and writeln. Apparently Lua's print is similar to writeln of Pascal. Do we have something similar to write of Pascal? How can consecutive print commands send their output to the same line?
print("Hello")
print("World")
Output:
Hello
world
I want to have this:
Hello world
Use io.write instead print, which is meant for simple uses, like debugging, anyway.
Expanding on lhf's correct answer, the io library is preferred for production use.
The print function in the base library is implemented as a primitive capability. It allows for quick and dirty scripts that compute something and print an answer, with little control over its presentation. Its principle benefits are that it coerces all arguments to string and that it separates each argument in the output with tabs and supplies a newline.
Those advantages quickly become defects when detailed control of the output is required. For that, you really need to use io.write. If you mix print and io.write in the same program, you might trip over another defect. print uses the C stdout file handle explicitly. This means that if you use io.output to change the output file handle, io.write will do what you expect but print won't.
A good compromise can be to implement a replacement for print in terms of io.write. It could look as simple as this untested sample where I've tried to write clearly rather than optimally and still handle nil arguments "correctly":
local write = io.write
function print(...)
local n = select("#",...)
for i = 1,n do
local v = tostring(select(i,...))
write(v)
if i~=n then write'\t' end
end
write'\n'
end
Once you are implementing your own version of print, then it can be tempting to improve it in other ways for your application. Using something with more formatting control than offered by tostring() is one good idea. Another is considering a separator other than a tab character.
As an alternative, just build up your string then write it out with a single print
You may not always have access to the io library.
You could use variables for "Hello" and "World". Then concatenate them later. Like this:
local h = "Hello"
local w = "World"
print(h..w)
It will be display, in this case, as "HelloWorld". But that's easy to fix. Hope this helped!
Adding on to #Searous's answer, try the following.
local h = "hello"
local w = "world"
print(h.." "..w)
You can concatenate both together, just concatenate a space between both variables.
local h = "Hello"
local w = "World!"
print(h, w)
Related
So I am trying to make a language in lua, and I am replacing the word "output" with "print" and a few more words, but if someone does output("output") it also replaces it. How can i check if it is in a string?
Code:
output('trying to make a new language in lua')
output('\n')
local file = io.open(arg[1],"r")
local code = file:read "*a"
local filename = arg[1]
local function execute()
code = code:gsub("output","print")
code = code:gsub("void","function")
code = code:gsub("{}}","end")
local newfile = io.open(filename:gsub("idk","lua"),"w")
newfile:write(code)
newfile:close()
os.execute("lua test.lua")
end
execute()
Lua patterns are generally unsuitable to build a parser for a programming language; neither do they have the full expressive power of regular expressions required for tokenization (lexical analysis) nor do they get anywhere near the power of a context-free grammar (CFG, syntactical analysis) required for constructing the abstract syntax tree even though they provide some advanced features such as bracket matching which exceed regular expression capabilities.
As a beginner, you'll probably want to start with a handwritten tokenizer; as your language only operates at a token replacement level at this stage, you can simply replace identifier tokens.
You don't need string replacement (gsub) to implement variable renames like print to output when you are in control of how the script is executed: Just replace the global print variable with an output variable holding the print function (you may want to do this only in the environment the scripts written in your language run in):
output = print
print = nil
my problem is I need to write a Lua code to interpret a text file and match lines with a pattern like
if line_str:match(myPattern) then do myAction(arg) end
Let's say I want a pattern to match lines containing "hello" in any context except one containing "hello world". I found that in regex, what I want is called negative lookahead, and you would write it like
.*hello (?!world).*
but I'm struggling to find the Lua version of this.
Let's say I want a pattern to match lines containing "hello" in any context except one containing "hello world".
As Wiktor has correctly pointed out, the simplest way to write this would be line:find"hello" and not line:find"hello world" (you can use both find and match here, but find is probably more performant; you can also turn off pattern matching for find).
I found that in regex, what I want is called negative lookahead, and
you would write it like .*hello (?!world).*
That's incorrect. If you checked against the existence of such a match, all it would tell you would be that there exists a "hello" which is not followed by a "world". The string hello hello world would match this, despite containing "hello world".
Negative lookahead is a questionable feature anyways as it isn't trivially provided by actually regular expressions and thus may not be implemented in linear time.
If you really need it, look into LPeg; negative lookahead is implemented as pattern1 - pattern2 there.
Finally, the RegEx may be translated to "just Lua" simply by searching for (1) the pattern without the negative part (2) the pattern with the negative part and checking whether there is a match in (1) that is not in (2) simply by counting:
local hello_count = 0; for _ in line:gmatch"hello" do hello_count = hello_count + 1 end
local helloworld_count = 0; for _ in line:gmatch"helloworld" do helloworld_count = helloworld_count + 1 end
if hello_count > helloworld_count then
-- there is a "hello" not followed by a "world"
end
Acordding to the documentation of maxima, with_stdout is a function that evaluates some expressions and writes the output according to this expressions to a file f. I tried to use this function with a simple example:
with_stdout ("data.txt", for x:0 thru 10 do print (x, x^2, x^3))$
But the output look like this:
<mth><n>0</n><st> </st><n>0</n><st> </st><n>0</n><st> </st></mth><mth><n>1</n><st> </st><n>1</n><st> </st><n>1</n><st> </st></mth><mth><n>2</n><st> </st><n>4</n><st> </st><n>8</n><st> </st></mth><mth><n>3</n><st> </st><n>9</n><st> </st><n>27</n><st> </st></mth><mth><n>4</n><st> </st><n>16</n><st> </st><n>64</n><st> </st></mth><mth><n>5</n><st> </st><n>25</n><st> </st><n>125</n><st> </st></mth><mth><n>6</n><st> </st><n>36</n><st> </st><n>216</n><st> </st></mth><mth><n>7</n><st> </st><n>49</n><st> </st><n>343</n><st> </st></mth><mth><n>8</n><st> </st><n>64</n><st> </st><n>512</n><st> </st></mth><mth><n>9</n><st> </st><n>81</n><st> </st><n>729</n><st> </st></mth><mth><n>10</n><st> </st><n>100</n><st> </st><n>1000</n><st> </st></mth>
instead of writting a table with three columns as it is supposed to do.
I don't even understand the first output. What I am missunderstanding or missing here?
--
It seems there is a bug triggered by Wxmaxima, I don't know if it is on maxima aswell.
Regards.
Apparently wxMaxima overrides the default print function to generate XML tags (stuff like <foo> ... </foo>) which wxMaxima uses to indicate how stuff is displayed. I don't know if it's possible to directly call the default print function in wxMaxima; maybe, maybe not.
I can see a few options. (1) Call grind instead, which outputs the so-called 1-dimensional output. That's probably more suitable for file output anyway.
(2) Call printf, e.g. printf(true, "~a, ~a, ~a~%", x, x^2, x^3). printf recognizes many output options, as described by ? printf. It's possible printf calls are also intercepted by wxMaxima, I haven't tried it.
(3) Use the plain text, console Maxima interface, then print is sure to be the default.
Suppose in a (wx)Maxima session I have the following
f:sin(x);
df:diff(f,x);
Now I want to have it output a text file containing something like, for example
If $f(x)=\sin(x)$, then $f^\prime(x)=\cos(x)$.
I found the tex and tex1 functions but I think I need some additional string processing to be able to do what I want.
Any help appreciated.
EDIT: Further clarifications.
Auto Multiple Choice is a software that helps you create and manage questionaires. To declare questions one may use LaTeX syntax. From AMC's documentation, a question looks like this:
\element{geographie}{
\begin{question}{Cameroon}
Which is the capital city of Cameroon?
\begin{choices}
\correctchoice{Yaoundé}
\wrongchoice{Douala}
\wrongchoice{Abou-Dabi}
\end{choices}
\end{question}
}
As can be seen, it is just LaTeX. Now, with a little modification, I can turn this example into a math question
\element{derivatives}{
\begin{question}{trig_fun_diff_1}
If $f(x)=\sin(x)$ then $f^\prime(0)$ is
\begin{choices}
\correctchoice{$1$}
\wrongchoice{$-1$}
\wrongchoice{$0$}
\end{choices}
\end{question}
}
This is the sort of output I want. I'll have, say, a list of functions then execute a loop calculating their derivatives and so on.
OK, in response to your updated question. My advice is to work with questions and answers as expressions -- build up your list of questions first, and then when you have the list in the structure that you want, then output the TeX file as the last step. It is generally much clearer and simpler to work with expressions than with strings.
E.g. Here is a simplistic approach. I'll use defstruct to define a structure so that I can refer to its parts by name.
defstruct (question (name, datum, item, correct, incorrect));
myq1 : new (question);
myq1#name : "trig_fun_diff_1";
myq1#datum : f(x) = sin(x);
myq1#item : 'at ('diff (f(x), x), x = 0);
myq1#correct : 1;
myq1#incorrect : [0, -1];
You can also write
myq1 : question ("trig_fun_diff_1", f(x) = sin(x),
'at ('diff (f(x), x), x = 0), 1, [0, -1]);
I don't know which form is more convenient for you.
Then you can make an output function similar to this:
tex_question (q, output_stream) :=
(printf (output_stream, "\\begin{question}{~a}~%", q#name),
printf (output_stream, "If $~a$, then $~a$ is:~%", tex1 (q#datum), tex1 (q#item)),
printf (output_stream, "\\begin{choices}~%"),
/* make a list comprising correct and incorrect here */
/* shuffle the list (see random_permutation) */
/* output each correct or incorrect here */
printf (output_stream, "\\end{choices}~%"),
printf (output_stream, "\\end{question}~%));
where output_stream is an output stream as returned by openw (which see).
It may take a little bit of trying different stuff to get derivatives to be output in just the format you want. My advice is to put the logic for that into the output function.
A side effect of working with expressions is that it is straightforward to output some representations other than TeX (e.g. plain text, XML, HTML). That might or might not become important for your project.
Well, tex is the TeX output function. It can be customized to some extent via texput (which see).
As to post-processing via string manipulation, I don't recommend it. However, if you want to go down that road, there are regex functions which you can access via load(sregex). Unfortunately it's not yet documented; see the comment header of sregex.lisp (somewhere in your Maxima installation) for examples.
I've got a string like "foo%20bar" and I want "foo bar" out of it.
I know there's got to be a built-in function to decode a URL-encoded string (query string) in Emacs Lisp, but for the life of me I can't find it today, either in my lisp/ folder or with Google.
What is it called?
url-unhex-string
In my case I needed to do this interactively. The previous answers gave me the right functions to call, then it was just a matter of wrapping it a little to make them interactive:
(defun func-region (start end func)
"run a function over the region between START and END in current buffer."
(save-excursion
(let ((text (delete-and-extract-region start end)))
(insert (funcall func text)))))
(defun hex-region (start end)
"urlencode the region between START and END in current buffer."
(interactive "r")
(func-region start end #'url-hexify-string))
(defun unhex-region (start end)
"de-urlencode the region between START and END in current buffer."
(interactive "r")
(func-region start end #'url-unhex-string))
Add salt, I mean bind to keys according to taste.
Emacs is shipped with a URL library that provides a bunch of URL parsing functions—as huaiyuan and Charlie Martin already pointed out. Here is a small example that'd give you an idea how to use it:
(let ((url "http://www.google.hu/search?q=elisp+decode+url&btnG=Google+keres%E9s&meta="))
;; Return list of arguments and values
(url-parse-query-string
;; Decode hexas
(url-unhex-string
;; Retrieve argument list
(url-filename
;; Parse URL, return a struct
(url-generic-parse-url url)))))
=> (("meta" "") ("btnG" "Google+keresés") ("/search?q" "elisp+decode+url"))
I think is better to rely on it rather than Org-mode as it is its main purpose to parse a URL.
org-link-unescape does the job for very simple cases ... w3m-url-decode-string is better, but it isn't built in and the version I have locally isn't working with Emacs 23.
You can grab urlenc from MELPA and use urlenc:decode-region for a region or urlenc:decode-insert to insert your text interactively.
I think you're making it a little too hard: split-string will probably do most of what you want. For fancier stuff, have a look at the functions in url-expand.el; unfortunately, many of them don't have doc-strings, so you may have to read code.
url-generic-parse-url looks like a potential winner.