打印

Python 和 Lua 学习比较 (转)

[复制链接]
2284|6
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主

好记性不如烂笔头。
作的笔记以后也能来再看看。

python有多种语言写成的版本,这里只记录C/C++写的版本,lua本身是使用标准C/C++编写的。

所以各位同学知道C的强大了吧,我觉得作为程序员,应该都要学一下C/C++,这是你以后成长的奠基石。以后你如果不爽python或者lua了,自己编一种新的脚本语言,^_^

python和lua都是解释类语言,不用编译和链接,支持动态类型语言,意思就是这两个家伙都支持变量的类型变化,比如:

python:

>>> type(a) 
''' 输出
#Traceback (most recent call last):
#  File "<stdin>", line 1, in <module>
#NameError: name 'a' is not defined
'''
>>> a = "123"
>>> type(a) # 输出 <class 'str'>
>>> id(a) # 输出 35672112 - 每个人的结果不一样
>>> a = 12
>>> type(a) # 输出 <class 'int'>
>>> id(a) # 输出 1488898480 - 每个人的结果不一样
>>> a = 12.3
>>> type(a) # 输出 <class 'float'>
>>> id(a) # 输出 5734688 - 每个人的结果不一样
>>> 0/0 '''作死除法
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
'''

lua:

--[[
    lua多行注释
--]] --这里习惯在前面加上'--'
> type(a) -- 输出 nil
> a = "123"
> type(a) -- 输出 string
> a = 12
> type(a) -- 输出 number
> a = 12.3
> type(a) -- 输出 number
> 0/0 -- 输出 nan  意思就是Not a Number 不是数字
> type(0/0) -- 输出 number
--[[
    上面是否让你意外呢? 虽然是nan 但是它的类型还是number的
--]]

上面的代码演示了最基本的类型,在python中,使用未定义的变量会报错,而在lua中,只是简单的nil类型数据,相对于python,lua没有id函数,把所有的整数,浮点数都统称为number类型。细看python,我们发现虽然我们的变量a没有变,但是通过id函数,我们看出来了,a其实还是变了,这个具体的变法,我们不需要关心,我们只需要了解有这么回事,C/C++程序员知道,这里其实是存放a内容的内存地址变了,是一个新的对象。至于0除以0的问题,大家看注释了解就好了。
lua包含的数据类型有nil 、boolean 、number 、string 、table 、function 、userdata和thread。
Python后面再总结。

python和lua的提示也要了解一下,后面就不提示这个内容了。
python 默认提示 >>> ; 继续行提示 …
lua 默认提示 > ; 继续行提示 >>
前面不带符号的就是计算的输出了。
编码格式的话,我觉得如果没有必要,尽量都用UTF8,以后你会感谢我的^_^。

注释的方法,我已经放在上面的代码注释中了。


相关帖子

沙发
gaoyang9992006|  楼主 | 2018-9-9 23:14 | 只看该作者
在继续学习之前,我总结了个查询lua API的方法
for k,v in pairs(_G) do print(k,v) end #它会告诉我们lua有哪些可用table或者function
至于python,则是通过dir内建函数
import builtins
dir(builtins)#跟lua一样,查看当前内建的变量和函数,模块
dir()#查看当前定义的变量,函数,模块
import sys
dir(sys)#查看该sys包下可用的变量,函数,模块
计算能力的话,两者都一样,都可以当计算器使用
python:
>>> 2 + 2
4 #前面没有符号,这是python的输出结果
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # 除法总是返回一个浮点数
1.6
>>> 5 // 3 #取整
1
>>> 5 % 3 #取余
2
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
>>> 3 * 3.75 / 1.5
7.5 #整数与浮点数的计算,python会把整数转换成浮点数
>>> 7.0 / 2
3.5
lua返回的结果是跟python一样的,所以代码就不给出了。虽然输出的结果一样,但是我们要知晓,python区分int和float,lua都是number.

使用特权

评论回复
板凳
gaoyang9992006|  楼主 | 2018-9-9 23:16 | 只看该作者
下面来看看两者的幂运算符和对待未申明变量的区别
python:
>>> 5**2 #幂运算符 **
25 # 这里是 int
>>> n  # 试图访问未申明变量
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
lua:

> 5^2 --幂运算符 ^
25.0 -- 这里虽然是number,但是是浮点数,c程序员懂为什么
> n
nil

在交互模式下,python还提供了一个功能就是保留当前的计算结果,lua未提供。
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _ #这里的 _ 指的就是上次的计算结果12.5625
113.0625
>>> _ + 1
114.0625
  • 注:记住 python的_是只读的,切忌对它赋值。如果你这么做了,那就加一句 del _

虽然python还为我们提供了强大的Decimal、Fraction和complex number,这里就不一一介绍了。


使用特权

评论回复
地板
gaoyang9992006|  楼主 | 2018-9-9 23:19 | 只看该作者
在交互模式下两者对字符串的输出稍显差异
python:
>>> 'spam eggs'
'spam eggs' #这里会有单引号括起来,表示是字符串
>>> print('spam eggs') #打印函数
spam eggs
>>> s = 'First line.\nSecond line.'  # \n代表新行
>>> s  # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s)  # with print(), \n produces a new line
First line.
Second line.
lua:

> 'spam eggs'
spam eggs -- lua的话就是普通的打印
> print('spam eggs') #打印函数
spam eggs
> print('spam eggs')
spam eggs
> s = 'First line.\nSecond line.' -- \n代表新行
> s
First line.
Second line.
对于单引号,双引号的相互嵌套,或者反斜杠\的转义,两者没有任何区别。
python:

>>> print('spam eggs')  # single quotes
spam eggs
>>> print('doesn\'t')  # use \' to escape the single quote...
doesn't
>>> print("doesn't")  # ...or use double quotes instead
doesn't
>>> print('"Yes," he said.')
"Yes," he said.
>>> print("\"Yes,\" he said.")
"Yes," he said.
>>> print('"Isn\'t," she said.')
"Isn\'t," she said.

虽然有那么多写法,但是我觉得,作为一名优秀的程序员,我们还是不要窜来窜去的,对字符使用统一的写法,要么用'',要么用"",否则别人看了你的代码一定会头疼的^_^

有时候我们又不想要转义。
假如有这样一个目录 C:\name我们需要打印出来。

python:

>>> print("C:\name") # 结果,这里的\n被当成是换行符了,lua也是这结果
C:\some
ame

共同的解决方法是 print("C:\\name"),不过python还提供了另一种方法就是print(r"C:\name") 叫 raw strings。
python还对多行字符串提供了更加方便的解决方法"""..."""或者'''...''',自动读取换行符如果不想要换行符可以加转义符\

python:

print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to



使用特权

评论回复
5
gaoyang9992006|  楼主 | 2018-9-9 23:21 | 只看该作者
下面是两者拼接字符串的区别
python:
>>> print("un" + "ium") #能拼接两个常量字符串
unium
>>> a = "un"
>>> print(a + a + "ium") #也能拼接变量(类型需要是str,否则报错)和常量字符串,lua中的加号不能拼接字符串,但有其他功能
ununium
>>> print("un" "ium" "un" "ium")
'''
自动拼接相邻的字符串,不过这个只能拼接常量字符串,不能拼接变量和常量字符串;但是可以用来对很长的打印信息分行,打印结果也是单行的。lua不行
'''
uniumunium
>>> print(a*3) #这个比较厉害,可以对字符串做乘法,意思就是重复字符串,lua不可以
ununun
lua:

> print("un" .. "ium") -- 类似python的+,但是python不具有这个操作符
> a = "un"
> print(a .. a .. "ium") -- 类似python的+
ununium
> print(10 .. 20) -- 还能连接数字,输出类型是string,注意点点要跟数字10分开,不然会被当成小数的。
1020
> print(10 ..20) -- 不推荐这样写
1020
> a = "10"
> print(a + 1) -- 当一个string加number的时候,lua会先判断这个string能否转换成number(tonumber函数),能就得出加出来的数,否则报错
11.0
> a = "10a"
> print(a+1) -- 这里就报错了
stdin:1: attempt to perform arithmetic on a string value (global 'a')
stack traceback:
        stdin:1: in main chunk
        [C]: in ?
对字符串中某个字符的读取也不一样,python提供的功能更强大,lua只能走string的函数
python:

>>> # 在python中索引起步是0
>>> a = "1234567"
>>> print(a[0])
1
>>> print(a[-1])
7
>>> print(a[2:4]) # : 这个符号对应的区间是:[) 前面闭区间,后面开区间
34
>>> print(a[2:0]) # 等同 print(a[-5:-7])
    #无输出
>>> print(a[-3:-1])
56
>>> print(a[:2])
12
>>> print(a[2:])
34567
>>> a[8] # 越界访问
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> a[-8:] # 越界,输出全部
'1234567'
'''
对应的字符串索引图表就是
+---+---+---+---+---+---+---+---+---+---+
     |   | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
+---+---+---+---+---+---+---+---+---+---+
         0   1   2   3   4   5   6   7   8
-9  -8  -7  -6  -5  -4  -3  -2  -1
'''
>>> a[0] = "a" # 不能赋值
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> len(a) #查看字符串长度
7
lua:

> -- 在lua中索引起步是1,嘿嘿,区别于各种语言
> a = "1234567"
> print(string.sub(a,1)) -- 当然你要把这里的1改成0也是可以的,不推荐
1234567
> print(string.sub(a,2,1)) -- 无输出

> print(string.sub(a,3,3)) -- 等同python的a[2:3],python不许这种写法:a[2:2]。
> -- 所以我们就知道了,对于lua,它的区间是:[] 前后闭区间
3
> string.sub(a,8) -- 越界了,无输出

> string.sub(a,-8) -- 越界了,输出全部
1234567
--[[
对应的字符串索引图表就是,
+---+---+---+---+---+---+---+---+---+---+
     |   | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
+---+---+---+---+---+---+---+---+---+---+
     0   1   2   3   4   5   6   7   8   9
-9  -8  -7  -6  -5  -4  -3  -2  -1
--]]
> string.len(a) --查看字符串长度
7

对于用正向索引还是负向索引看哪个用的方便吧,一般用正向的。
通过上面的比较,python对字符串访问提供的功能更多,lua要更接近C的方式一点(只能通过函数操作)。

python还有list类型,lua可以通过table的方式实现类似的功能,看例子:
python:

>>> lst = [1,4,9,16]
>>> type(lst)
<class 'list'>
>>> lst[0] # []的访问跟上面字符串的访问一样
1
>>> lst[1]
4
>>> lst[2]
9
>>> lst[1:10] # lua不支持
[4, 9, 16]
>>> lst[-1]
16
>>> id(lst)
35530696
>>> id(lst[:]) # 每次[]操作,返回都是新的list对象
35530888
>>> lst2 = [25,36]
>>> lst + lst2 # python还支持两个list的串联
[1, 4, 9, 16, 25, 36]
>>> lst[3] = 81 # list不同于str,可以赋值
>>> lst
[1, 4, 9, 81]
>>> lst.append(100) # 通过append函数追加数据
>>> lst
[1, 4, 9, 81, 100]

>>> # python不仅可以单个赋值还能区间赋值 这个lua没有
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # 替换成大写
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # 删除它们
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # 用一个空的来清空这个list
>>> letters[:] = []
>>> letters
[]
>>> len(letters) # 使用函数 len 查看容量
0

>>> letters = [1,2,3,"a","b"] # 虽然python支持,但是我们最好不要这样做,数据类型最好要保持一致
>>> letters
[1, 2, 3, 'a', 'b']

>>> a = ['a', 'b', 'c'] # python还支持list嵌套
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

lua:

> lst = {1,4,9,16}
> lst
table: 00448638
> lst[1] -- lua从索引1开始
1
> lst[2]
4
> lst[3]
9
> lst[-1] -- lua的table []操作不支持负数访问
nil
> lst1 = {25,36}
> lst + lst2 -- lua 不支持 table相加,如果要实现这个功能需要借助table的函数,后面再说~
stdin:1: attempt to perform arithmetic on a table value (global 'lst')
stack traceback:
        stdin:1: in main chunk
        [C]: in ?
> lst[4] = 81 -- lua也可以赋值
> lst[4]
81
> #lst -- 通过 # 来取得 table 的容量
4

> letters = {1,2,3,"a","b"} -- 虽然lua可以这样做,但是我们尽量保证我们的table数据类型一致
> letters[1]
1
> letters[4]
a

> a = {"a","b","c"} —— lua也支持table嵌套
> n = {1,2,3}
> x = {a,n}
> x[1][1]
a
> x[2][1]
1



使用特权

评论回复
6
gaoyang9992006|  楼主 | 2018-9-9 23:22 | 只看该作者
最后我们再来看一下两者的打印函数 print
python:
>>> help(print) # 使用help函数,我们可以看到它的文档解释
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

>>>#sep 参数表示间隔字符串输出
>>>#end 参数表示打印结束后的字符串输出
>>>#如果参数不明白,下面的例子看了就懂了
>>> print(1,2,3,4,5)
1 2 3 4 5
>>> print(1,2,3,4,5,sep=",",end=".")
1,2,3,4,5.>>>#这里由于把end的参数改成.所以没有回车

lua:
>-- lua 查文档 就一个 print (···),它建议我们用string.format来定制自己的打印格式,这个函数后面再细说。

> print(1,2,3,4,5) -- lua 默认分的很开
1       2       3       4       5

使用特权

评论回复
7
gaoyang9992006|  楼主 | 2018-9-9 23:22 | 只看该作者
未完待续。。。

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

认证:西安公路研究院南京院
简介:主要工作从事监控网络与通信网络设计,以及从事基于嵌入式的通信与控制设备研发。擅长单片机嵌入式系统物联网设备开发,音频功放电路开发。

1895

主题

15628

帖子

197

粉丝